<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by TradingBot con Ale on Medium]]></title>
        <description><![CDATA[Stories by TradingBot con Ale on Medium]]></description>
        <link>https://medium.com/@arrabitoster?source=rss-bca388a41cd1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2dTDxaMvNTFL7y1oLy9GUQ.png</url>
            <title>Stories by TradingBot con Ale on Medium</title>
            <link>https://medium.com/@arrabitoster?source=rss-bca388a41cd1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:57:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arrabitoster/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[+117% in 4 Years: Freqtrade implementation of a dual momentum strategy]]></title>
            <link>https://medium.com/@arrabitoster/117-in-4-years-freqtrade-implementation-of-a-dual-momentum-strategy-dfbdd721fbaf?source=rss-bca388a41cd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfbdd721fbaf</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[freqtrade]]></category>
            <dc:creator><![CDATA[TradingBot con Ale]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 12:23:32 GMT</pubDate>
            <atom:updated>2026-06-05T12:23:32.106Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Walk-forward methodology, out-of-sample results, and what most backtests get wrong.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDch-eX9jBs8o5u8F1Pzdg.png" /><figcaption>dry run of the dual momentum strategy</figcaption></figure><p>Most crypto backtests are useless. Not because the strategy is bad, but because the test is. <br> <br> Overfitting on a single window. Parameters tuned on the same period they’re tested on. No out-of-sample data. A bull run that makes everything look good. <br> <br> This article documents the methodology I used to build and validate a cross-sectional momentum strategy on Bybit USDT perpetual futures — and why I think the results are more credible than a standard backtest. <br> <br> The headline numbers: <strong>+117% total return over 4.4 years (Jan 2022 — May 2026), 19.4% CAGR, 10.6% max drawdown, Sharpe 1.11.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*kPs0aEYj-hzcfFrIiaxvZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU2c0nVyko2YHqz2uagv0g.png" /></figure><h3><strong>The Strategy: Dual Momentum as a Portfolio</strong></h3><p>The strategy is built on Dual Momentum — a framework that combines two distinct momentum signals. Cross-sectional momentum (CSM) ranks assets relative to each other and selects the strongest and weakest performers. Absolute momentum (time-series) asks a separate question: is the market itself in a positive trend? In this implementation, the CSM layer ranks the top 20 crypto assets by recent return and allocates to the top 3 (long) and bottom 3 (short) at each rebalance. The absolute momentum layer acts as a regime gate: when BTC falls below its 30-day moving average, the entire portfolio shuts down. At any given time the strategy holds up to 6 simultaneous positions, weighted by inverse volatility — it operates as a continuously rebalanced portfolio, not a sequence of independent trades. This distinction matters for how performance is measured and interpreted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GnmWp_AnkI1WkO33nb7VA.png" /></figure><p><strong>The Setup</strong> <br> <br> The strategy runs on the top 20 crypto assets by market cap, traded as USDT perpetual futures on Bybit (daily bars). Every 20 days, it ranks assets by 8-day momentum (excluding the last day of the window — more on this later), goes <br> long the top 3 and short the bottom 3, weighted by inverse volatility. <br> <br> The whole thing is implemented in Freqtrade (https://www.freqtrade.io/), an open-source Python trading framework<br> <br> <strong>The Framework: Freqtrade</strong> <br> <br> The strategy runs on Freqtrade (https://www.freqtrade.io/), an open-source Python backtesting and live trading framework. It supports daily OHLCV data from Bybit, custom indicator logic, portfolio-level rebalancing, and a built-in hyperparameter optimizer (Hyperopt). <br> <br> Universe: top 20 crypto assets by market cap, USDT perpetual futures, daily bars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtO5GgMgEsqGEJfUYhpnIQ.png" /></figure><h3><strong>Walk-Forward Validation</strong></h3><p>The standard mistake in strategy development is optimizing parameters on the full dataset and reporting that as performance. The model fits the noise in the data and the result is meaningless. <br> <br> Walk-forward validation splits the data into non-overlapping windows: <br> <br> — <strong>Training window</strong>: optimize parameters on this period only <br> — <strong>Out-of-sample window</strong>: lock parameters, run the strategy without touching them</p><p><strong>Parameters</strong> were optimized exclusively on the training window using Freqtrade’s Hyperopt with SharpeHyperOptLoss and — spaces buy sell — the latter constraint is critical. Without specifying spaces, Hyperopt also modifies the ROI table and stop-loss, which fundamentally changes the strategy’s behavior and produces parameters that are impossible to interpret. <br> <br><strong>Results: Training vs Out-of-Sample</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*bIlPApSQlsWciTtSh5dnpQ.png" /></figure><p>OOS outperforming training is unusual and worth noting. Two possible explanations: the 2024–2026 period was structurally favorable for momentum strategies, or the parameters found in hyperopt captured a genuine signal rather than <br> noise. Probably both.</p><p><strong>What the Sharpe of 1.11 Actually Measures</strong> <br> <br> Freqtrade computes two different Sharpe ratios and it’s easy to confuse them. <br> <br> The trade-based Sharpe (0.54) measures the distribution of individual trade returns. This is not meaningful for a rebalancing strategy where positions overlap and are held simultaneously. <br> <br> The wallet-based Sharpe (1.11) measures the daily portfolio balance over time, annualized with √365. This is the correct metric for a strategy that operates as a continuous portfolio rather than a sequence of independent bets.</p><p><strong>Five Design Decisions That Affected Results</strong> <br> <br> A brief enumeration — the full explanation with data is on Substack: <br> <br> 1. <strong>Monday rebalancing</strong> — day-of-week has a documented and dramatic impact; Friday rebalancing leads to liquidation <br> 2. <strong>Skip-last-day lookback</strong> — removes short-term reversal noise from the momentum signal <br> 3. <strong>BTC MA30 as signal-quality gate</strong> — not a directional bet, but a filter on when the short signal is discriminating <br> 4. <strong>Inverse volatility position sizing</strong> — weights are proportional to 1/σ, normalized to sum to 1 <br> 5. <strong>Short leg in bull markets only</strong> — the short edge comes from relative underperformance in a rising universe, not decorrelation</p><h3>Full research note</h3><blockquote>The full breakdown — regime filter analysis, BTC correlation study for short entries, academic paper findings, and all design decisions with quantitative comparisons — <a href="https://backtestsnotsignals.substack.com/p/117-in-4-years-dual-momentum-on-crypto?r=2a708q">is on my newsletter</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfbdd721fbaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Momentum Strategy on the S&P 500 Delivered 23% CAGR From 2016 to 2026]]></title>
            <link>https://medium.com/@arrabitoster/a-momentum-strategy-on-the-s-p-500-delivered-23-cagr-from-2016-to-2026-e33d2a6ded32?source=rss-bca388a41cd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e33d2a6ded32</guid>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[cross-sectional-momentum]]></category>
            <category><![CDATA[momentum]]></category>
            <dc:creator><![CDATA[TradingBot con Ale]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 18:25:28 GMT</pubDate>
            <atom:updated>2026-04-19T20:55:51.907Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A simplified long-only portfolio built on the 100 largest current S&amp;P 500 constituents, rebalanced quarterly from 2016 to 2026.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*cCSTyPR_FJRPOVlT7EC7zw.jpeg" /></figure><p>A simple cross-sectional momentum portfolio on U.S. large caps turned out to be much more resilient than a frictionless backtest would suggest.</p><p>Using a long-only setup on the 100 largest current S&amp;P 500 constituents from 2016 to 2026, the strategy produced a strong gross result and remained interesting even after fixed commissions and a simplified tax drag. The edge became smaller, but it did not disappear.</p><h3>Results</h3><p>From the first rebalance on <strong>2016–01–04</strong> to the last rebalance on <strong>2026–01–02</strong>, this simplified long-only implementation delivered a strong but far from effortless profile.</p><p>Starting from <strong>100,000</strong>, the portfolio reached <strong>817,685</strong>, corresponding to a <strong>23% CAGR</strong>, a <strong>Sharpe ratio of 0.83</strong>, a <strong>Sortino ratio of 1.08</strong>, and a <strong>maximum drawdown of -35%</strong>.</p><p>That combination is the main reason I find the strategy interesting: the return is strong, but the path is clearly not smooth.</p><p>Questa terza frase finale è utile, perché fa da ponte alla spiegazione successiva.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJPpO2FPEFqOXJVFbLUY0Q.png" /><figcaption>monthly returns</figcaption></figure><h3>Strategy</h3><p>Cross-sectional momentum is a <strong>relative-strength strategy</strong>: instead of evaluating each stock in isolation, it ranks assets against one another and allocates capital to the strongest names.</p><p>In this implementation, the universe is a fixed set built from the <strong>100 largest current S&amp;P 500 constituents</strong>, the signal is a standard <strong>12–1 momentum measure</strong>, the portfolio is <strong>long-only</strong>, the selected names are held <strong>equal-weight</strong>, and the strategy is rebalanced <strong>quarterly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*K0MoKtX6x7_CKHoKwB8qqg.png" /><figcaption>a ranking example at each rebalance date</figcaption></figure><p>In a full implementation, the weakest names can be shorted as well. In this article, however, I focus on a simplified <strong>long-only</strong> version.</p><p>The portfolio is rebalanced <strong>quarterly</strong> and constructed with <strong>equal weights</strong> across the selected top-ranked assets. If N assets are held at rebalance date t, the portfolio return over the next holding period can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*BRr3gT8LGC68mlJjBeJ--A.jpeg" /></figure><p>where Pt​ is the set of assets selected at time t, and Ri,t+1​ is the return of asset i over the subsequent holding period.</p><h3>References</h3><p>Cross-sectional momentum has been studied extensively across markets and asset classes. Bird, Gao and Yeung (2017)<a href="#7023">¹</a> compare time-series and cross-sectional momentum across 24 markets and find positive results for both, although with materially different portfolio behavior. A more recent S&amp;P 500-focused study by Kivelä (2025)<a href="#2e38">²</a> also finds especially supportive evidence for long-only cross-sectional momentum.</p><h3>Full research note</h3><blockquote>This article is a condensed version of a longer research note. The full write-up, together with the companion notebook and supplementary material, is available on my Substack<a href="https://backtestsnotsignals.substack.com/p/cross-sectional-momentum-on-the-s?r=2a708q">³</a>.</blockquote><p>[1]: Bird, Ron, Xiaojun Gao, and Danny Yeung. 2017. <em>Time-series and cross-sectional momentum strategies under alternative implementation strategies</em>. <em>Australian Journal of Management</em>, 42(2), 230–251. <a href="https://www.researchgate.net/publication/298897632_Time-series_and_cross-sectional_momentum_strategies_under_alternative_implementation_strategies?utm_source=chatgpt.com">DOI / publisher page</a>.</p><p>[2]: Kivelä, Tuomas. 2025. <em>Cross-sectional and time-series momentum strategies’ performance in the S&amp;P 500 index</em>. Bachelor’s thesis, LUT University. <a href="https://lutpub.lut.fi/bitstream/handle/10024/171138/Bachelorsthesis_Kivela_Tuomas.pdf?isAllowed=y&amp;sequence=1&amp;utm_source=chatgpt.com">PDF / repository page</a>. current S&amp;P 500 constituents by market capitalization</p><p>[3]: Alessandro Arrabito. 2026. <a href="https://backtestsnotsignals.substack.com/p/cross-sectional-momentum-on-the-s?r=2a708q">Cross-Sectional Momentum on the S&amp;P 500 Still Beats SPY After Costs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e33d2a6ded32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart scalping DCA and get 10% per month]]></title>
            <link>https://medium.com/@arrabitoster/smart-scalping-dca-and-get-10-per-month-355c64ef0bc3?source=rss-bca388a41cd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/355c64ef0bc3</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[tradingview]]></category>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[scalping]]></category>
            <category><![CDATA[freqtrade]]></category>
            <dc:creator><![CDATA[TradingBot con Ale]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 17:56:57 GMT</pubDate>
            <atom:updated>2024-11-16T21:46:06.197Z</atom:updated>
            <content:encoded><![CDATA[<p>I developed a scalping strategy for TradingView and FreqTrade that leverages market fluctuations. It doesn’t follow trends or go against them, but rather utilizes the historical volatility of a token to apply DCA in a scientific and calculated way through Bayesian optimization (using backtesting.py). It employs money management to always remain profitable, preventing the bot from getting stuck.</p><p>In this article, I discuss how to optimize a trading strategy and show results that highlight the impact of optimization on strategy performance. The core elements of this work are Bayesian optimization, token decorrelation, and money management implemented through DCA.</p><p>The results presented in the article were generated through backtesting and optimization on data from June 2021 to June 2024, using a 5-minute timeframe, with margin and leverage futures/perpetual instruments like DOGEUSDT and XMRUST on the ByBit exchange. As I write this article, the strategy is already running live on ByBit.</p><p><strong>Hope and goals</strong></p><p>Initially, I considered a highly volatile cryptocurrency like Dogecoin, aiming to open as many trades as possible, use leverage, and operate both long and short to be active in all market phases, targeting a profit of around 10% per month. I then applied the same approach to a decorrelated asset like XMRUSDT to diversify the investment.</p><p><strong>Strategy</strong></p><p>From a technical point of view, the strategy is based solely on the Bollinger bands, which act as the trade opening trigger: the rising cross with the lower band will be the signal for a long entry, vice versa, a short one. In this sense the strategy does not differ from many others based on this indicator but the backbone of the entire project is the optimization setup, which allows you to obtain for any token the parameters necessary to respect the objective of trading with the DCA without being stuck in a trade for a long time and without being liquidated. So money management together with optimization is the other fundamental element, which is why I used DCA, i.e. it is possible to mediate the first entry which I will call “Base Order” through further trades which I will call safety order. Each Safety order occurs after a fixed percentage deviation, starting from the Base Order and subsequently from the last safety order placed. In addition to the fixed deviation there is a further deviation (safety order scale) which is incremental and varies as the depth of the safety order increases. The volume will also be incremental, so I define a ratio that for each safety order allows the volume to be increased so that the average price can follow the price. All these parameters, such as: number of safety orders, size, deviation, ratio of the deviation and size and finally number of possible safety orders will constitute the variables to be fed to the optimizer to obtain a satisfactory solution.</p><p><strong>DCA</strong></p><p>Dollar Cost Averaging (DCA) is an investment strategy where an investor divides up the total amount to be invested across periodic purchases of a target asset in an effort to reduce the impact of volatility on the overall purchase price. Instead of investing a large sum of money in a single purchase, DCA involves buying smaller amounts at regular intervals over time, regardless of the asset’s price fluctuations.</p><p>The key principle behind DCA is that by spreading out investments, you reduce the risk of making a substantial loss due to market volatility. It also removes the pressure of trying to time the market perfectly. DCA is commonly used in stock market investing and cryptocurrency trading to potentially lower the average cost per unit of the asset purchased over time.<br>Dollar Cost Averaging (DCA) can involve risks when applied to future trading with leverage. <br>Here are some key risks to consider:</p><p><strong>Increased Exposure</strong>: When using leverage, each dollar invested controls a larger amount of asset. This magnifies both potential gains and losses. DCA can increase exposure over time as more purchases are made, potentially amplifying losses if the asset’s price declines.</p><p><strong>Margin Calls</strong>: Leverage involves borrowing funds to increase trading position sizes. If the value of the asset decreases significantly, it may trigger a margin call. This requires the trader to add more funds to maintain the position or risk liquidation.</p><p><strong>Volatility Impact</strong>: DCA involves buying assets at regular intervals regardless of price movements. In a highly volatile market, this can result in purchasing assets at higher prices during upswings and lower prices during downturns. This may affect the overall average cost.</p><p><strong>Market Timing Risk</strong>: DCA does not attempt to time the market, which means the investor may continue buying even if the asset’s price is declining. This strategy assumes that the market will recover over time, which may not always be the case in leveraged trading.</p><p><strong>Liquidity Risk</strong>: In leveraged trading, especially with futures, liquidity can vary. Low liquidity can affect trade execution, slippage, and the ability to exit positions swiftly, especially during market stress.</p><p><strong>Over-leveraging</strong>: Using too much leverage can lead to excessive risk and potential losses that exceed the initial investment. DCA combined with leverage requires careful monitoring of position sizes and margin requirements to avoid overextending.</p><p>In summary, while DCA is a strategy aimed at reducing the impact of market volatility over time, applying it to leveraged trading introduces additional risks related to margin calls, volatility impact, and liquidity. Traders should carefully assess these risks and consider their risk tolerance and investment goals before implementing such strategies.</p><p><strong>Decorrelation</strong></p><p>The optimization process aimed to maximize equity and minimize liquidations, which I will discuss in the following paragraphs. The goal is to keep the bot constantly active and avoid it staying idle for long periods waiting for prices to reach targets. In this sense, diversification adds an additional layer of security. To prevent the bot from getting stuck, the strategy involves using pairs of coins that are decorrelated from each other, thereby increasing the likelihood of having a token actively trading at all times.</p><p><strong>Backtest with TradingView</strong></p><p>The strategy was initially drafted in Pinescript for TradingView. After defining the margin level, I started with 5x leverage and a capital of 500 USDT, conducting initial experiments to manually optimize parameters, achieving good equity and performance without extensive backtesting. The backtest on DOGEUSDT perpetual, listed on ByBit with a premium subscription and a 5-minute timeframe, covers approximately 3 months (20,000 candles). Meanwhile, the comprehensive backtest spans several years, starting from June 2021.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQQSFG79-XPjtcGgZKo4rQ.png" /><figcaption>Fig1. Equity showed in TradingView done with extended backtesting option</figcaption></figure><p>TradingView: Using the extended backtest shows a wonderful equity curve, but the number of trades and the profit over 3 years reveal an anomaly. In fact, the number of trades and results are only three times higher than those of the last 3 months, and since there were no margin calls, it’s evident that the bot remained stuck in trades for long periods. Therefore, I conducted a more thorough analysis with backtesting.py to understand what had happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLUsKJAWqJxF3oeN2tLX_w.png" /><figcaption>Fig.2 backtest done with backtesting.py</figcaption></figure><p>Running the same backtest, using the same algorithm and settings, yields more detailed insights into the equity. It’s possible to zoom in and view each individual trade starting from June 2021, but what’s clearly visible is that the bot was stuck in a trade from November 2021 to November 2022. It’s evident that under these conditions, the strategy is not viable, and therefore, it’s necessary to seek other parameters to make it profitable, as shown in the following images where optimal parameters were derived for DOGE and XMR through an extensive optimization process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doxxrslsHIKhsuWQSoTQzQ.png" /><figcaption>Fig.3 equity line of strategy with DOGE, the red line above show just a little period of inactivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8Kkwv__4-vXfbS6Tghbrg.png" /><figcaption>Fig.4 equity line of strategy with XMR, the red line above the equity show just a little period of inactivity that is different from the picture above related to DOGE token.</figcaption></figure><p>The two images show the equity curves of DOGE and XMR, which are decorrelated from each other, thereby increasing the likelihood that the bot never gets stuck in a trade.</p><p><strong>Margin and liquidation</strong></p><p>The strategy does not use stop-loss orders. In this regard, understanding the limits of leverage usage is a fundamental requirement. Margin management impacts all tools used, starting from TradingView, which evaluates margin by specifying the required percentage in settings, relative to available equity percentage. Similarly, Backtesting.py evaluates margin as a ratio with leverage; for instance, with leverage 2, there is a 50% margin relative to equity, as with TradingView. Freqtrade calculates margin much more precisely by directly interfacing with the exchange. Freqtrade utilizes the CCXT library to communicate with exchange APIs and calculates margin exactly as the exchange does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*cwbBVYa_Sd147pAiyk3_TA.png" /><figcaption>Freqtrade snippet to get liquidation price for ByBit</figcaption></figure><p>Attention, however, Freqtrade supports only isolated margin, which means the margin is not related to equity but rather to each individual investment. Therefore, if I invest 1000 USDT with leverage 5, the margin will be 20% plus the maintenance margin ratio, which for DOGEUSDT perpetual, at the time of writing this article, is 0.0075. Additionally, Fraqtrade considers an emergency cushion called “liquidation buffer,” which defaults to 5% and which I will use. Ultimately, isolated margin and the liquidation buffer greatly limit the possibilities of using leverage and capital, but also significantly reduce risk. This is because in the worst-case scenario, in the event of liquidation, only the involved position will be liquidated, whereas with “cross margin,” all capital contributes to the margin and therefore all capital is at risk. In the figure below, I show how Freqtrade calculates the liquidation level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*5ktqsgX3xD2Or6yIXe-JhA.png" /><figcaption>pinescript snippet of margin handler</figcaption></figure><p>Given this premise about leverage management, both on TradingView and especially on Backtesting.py, I had to align myself with the same conditions as Freqtrade so that the optimization would be meaningful and usable in the same way with Freqtrade and TradingView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*ibtXA8TFz5kgHFoXVh8inA.png" /><figcaption>TradingView custom margin call level for isolated margin</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*860IfF1LLHRpajhs0NwDoQ.png" /><figcaption>Backtesting.py custom margin call levels for isolated margin</figcaption></figure><p><strong>Backtest and parametrization</strong></p><p>The backtest was developed by parameterizing every relevant value that could influence the outcome. This included the parameters of the Bollinger Bands used to open a trade, and the parameters of Dollar Cost Averaging (DCA) such as: the size of the base order and additional orders (safety orders), price deviation to trigger safety orders, deviation and increment ratio of volume for each additional safety order, and finally the maximum number of safety orders allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*l-VJd2tbE_UM_olZ2nZv5A.png" /><figcaption>Parameter declaration in the Backtesting.py class</figcaption></figure><p><strong>Freqtrade and TradingView compliance</strong></p><p>The backtest was designed to produce results compatible with both TradingView and Freqtrade, allowing for quick activation of a bot using these tools. Future plans include custom bot development tailored to maximize profits while minimizing constraints during backtesting. The backtest took into account various bot implementation possibilities. For example, different trade management policies were implemented: all safety orders can be placed as limit orders with the first trade, or each safety order can be placed when candle close or spike reaches the safety order level.</p><p>It’s important to note the distinction between TradingView and FreqTrade. TradingView functions as a strategy definition platform where conditions trigger one or more orders (related to the same trade). Orders are executed through a broker emulation, and alerts are sent using entry/exit commands to instruct the exchange to perform actions. On the other hand, FreqTrade operates as a true bot connected to the exchange, enabling direct interaction via the Python CCXT library. This allows FreqTrade to not only place orders but also monitor the order book and track order status, ensuring a more active trade management approach compared to TradingView’s alert-based system. FreqTrade’s stricter constraints stem from its active trade management capabilities, contrasting with TradingView’s role limited to issuing alerts without further trade interaction.</p><p><strong>TradingView and DCA</strong></p><p>TradingView, through the entry instruction, can specify a limit order, allowing it to place both the base order and subsequent safety orders as limit orders. These orders will only be &quot;filled&quot; if the price reaches the specified level. This process is straightforward in that sense.</p><p>It’s crucial to consider that the take profit follows the average trade price. When a limit order is “filled,” the average trade price decreases, necessitating a recalculation of the take profit accordingly. Take profit can be specified using the strategy.exit function also via a limit order.</p><p><strong>IMPORTANT</strong>: This approach allows the backtest to utilize all OHLC candle data effectively. If it’s known in advance that the entry or exit order lies between the candle’s open and close, it can be considered “filled” at the specified price via entry or exit. This method can significantly enhance backtest performance but may increase susceptibility to parameter overfitting.</p><p>Alternatively, working in “trigger” mode activates orders only when the candle’s close reaches the target. This applies to DCA orders, safety orders, and take profit orders. The disadvantage is that orders will be “filled” at the open of the subsequent candle, introducing some randomness to the entry or exit price. Consequently, optimization may yield less performant results due to less precise price control, but it mitigates overfitting issues to some extent. However, there will likely be more slippage in this mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06XeepOSt2Bs3iOGvvQtBA.png" /><figcaption>TradingView snippet to place all safety orders at start with the base order</figcaption></figure><p><strong>Freqtrade and DCA</strong></p><p>Freqtrade does not allow for placing multiple trades simultaneously but does enable the modification of the current trade’s size. From an implementation standpoint, this involves managing the increment of the trade’s “size” when the price reaches the safety order level. Freqtrade then handles communication with the exchange to place an additional order effectively increasing the “size.”</p><p>Additionally, exiting for take profit at a specific price, which varies depending on the token, must be managed dynamically during the trade. This is done by evaluating the closing price of the candle, knowing that the exit price will correspond to the opening price of the subsequent candle.</p><p>All of this functionality is made possible through two callbacks provided by the Strategy class in Freqtrade. These callbacks allow for dynamic management of trade size and price targets, ensuring flexibility and adaptability during live trading scenarios.</p><pre>def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,<br>                            proposed_stake: float, min_stake: Optional[float], max_stake: float,<br>                            leverage: float, entry_tag: Optional[str], side: str,<br>                            **kwargs) -&gt; float:</pre><p>Freqtrade allows for changing the size of the current trade, enabling evaluation of the current price to decide whether to open a safety order. This flexibility is crucial for adjusting trade parameters dynamically based on real-time market conditions, ensuring adaptive trading strategies that can respond to price movements effectively.</p><pre>        if 1 &lt;= count_of_entries &lt;= self.settings[pair][&quot;so_count&quot;]:<br>            if (current_time - timedelta(minutes=timeframe_to_minutes(self.timeframe))) &gt;= filled_entries[(count_of_entries - 1)].order_filled_date.replace(tzinfo=timezone.utc):<br><br>                # safety_order_trigger is the offset from base order<br>                so_amount = self.settings[pair][&quot;so_amount&quot;] / trade.leverage<br>                safety_order_volume_scale = self.settings[pair][&quot;so_volume_scale&quot;]<br>                safety_order_trigger_price = rec_safety_order_price(count_of_entries, self.settings[pair][&quot;so_step_scale&quot;], self.settings[pair][&quot;so_deviation&quot;], trade.open_rate_requested, &quot;short&quot; if trade.is_short else &quot;long&quot;)<br>                if (current_price &gt;= safety_order_trigger_price and trade.is_short) or (current_price &lt;= safety_order_trigger_price and not trade.is_short):<br>                    try:<br>                        # This then calculates current safety order size<br>                        stake_amount = so_amount * math.pow(safety_order_volume_scale,(count_of_entries - 1)) #/ self._leverage<br>                        amount = stake_amount / current_price<br><br>                        #safety_order_price = trade.open_rate_requested * (1 - safety_order_trigger if not trade.is_short else 1 - safety_order_trigger)<br>                        logger.info(f&quot;{current_time}/{trade.pair} - so {count_of_entries}/{self.settings[pair][&#39;so_count&#39;]} at price {current_price} so_level {round(safety_order_trigger_price, 5)} with stake amount of {stake_amount * self._leverage} {trade.stake_currency} - liq:{round(trade.liquidation_price, 5)} - {round(amount * self._leverage, 4)} {trade.base_currency}&quot;)<br>                        return stake_amount, f&quot;SO{count_of_entries}&quot;</pre><p><strong>IMPORTANT</strong>: The backtest conducted with backtesting.py (and also TradingView) to adhere to the constraints mentioned above involves opening safety orders both as limit orders placed immediately with the first trade, as well as conditional orders triggered upon reaching the specified price for accumulation in the case of safety orders or for exiting in the case of take profit.</p><p><strong>Optimization</strong></p><p>Backtesting.py allows for optimization through two different strategies. The default strategy involves permuting all provided parameters within their specified ranges, which can generate an immense number of combinations even with a small set of parameters. To manage this, you can limit the number of attempts, ensuring you obtain the best configuration but potentially requiring extensive time. Alternatively, achieving optimal solutions is possible using a more sophisticated search method. Backtesting.py leverages the scipy module to perform Bayesian optimization, which can lead to optimal configurations more efficiently than exhaustive permutation.</p><p>Bayesian optimization is a method for optimizing complex and expensive-to-evaluate functions by using a surrogate model, often a Gaussian Process, to approximate the objective function. It balances exploration and exploitation through an acquisition function to efficiently determine the next point to sample, iteratively updating the model with new data. This approach is particularly effective in reducing the number of evaluations needed to find the optimal solution, making it ideal for hyperparameter tuning and other optimization tasks where evaluations are costly or time-consuming.</p><p><strong>A simple example: Optimizing a Mathematical Function</strong></p><p>Let’s optimize the function f(x)=sin⁡(3x)+x2−0.7xf(x) = \sin(3x) + x² — 0.7xf(x)=sin(3x)+x2−0.7x over the range x∈[0,2]x \in [0, 2]x∈[0,2].</p><ol><li><strong>Initialization</strong>:</li></ol><ul><li><strong>Select initial points</strong>: Randomly pick a few points in the range. For example, x1=0.5x_1 = 0.5x1​=0.5, x2=1.5x_2 = 1.5x2​=1.5.</li><li><strong>Evaluate</strong>: Calculate f(x1)f(x_1)f(x1​) and f(x2)f(x_2)f(x2​).</li></ul><p><strong>2. Surrogate Model</strong>:</p><ul><li><strong>Fit a Gaussian Process (GP)</strong>: Use the initial points and their evaluations to create a model that approximates the function.</li></ul><p><strong>3. Acquisition Function</strong>:</p><ul><li><strong>Choose next point</strong>: Use an acquisition function (e.g., Expected Improvement) to decide where to sample next. This balances exploring new areas and exploiting known good areas.</li><li><strong>Example</strong>: It might suggest sampling at x3=1.0x_3 = 1.0x3​=1.0.</li></ul><p><strong>4. Evaluation</strong>:</p><ul><li><strong>Evaluate f(x3)f(x_3)f(x3​)</strong>: Calculate the function value at the suggested point.</li></ul><p><strong>5. Update</strong>:</p><ul><li><strong>Update the model</strong>: Incorporate x3x_3x3​ and f(x3)f(x_3)f(x3​) into the GP model.</li></ul><p><strong>6. Iteration</strong>:</p><ul><li><strong>Repeat steps 3–5</strong>: Continue iterating, selecting new points, evaluating them, and updating the model until a stopping criterion is met (e.g., maximum iterations or convergence).</li></ul><h3>Visualization</h3><ul><li><strong>Initial Exploration</strong>: Random points are chosen and evaluated.</li><li><strong>Surrogate Model Update</strong>: The GP model is updated with each new point, refining the approximation.</li><li><strong>Acquisition Function</strong>: Guides the selection of the next sampling point based on the model’s uncertainty and potential improvement.</li></ul><h3>Outcome</h3><ul><li><strong>Optimal Solution</strong>: After several iterations, the process converges to the optimal value of xxx that minimizes or maximizes f(x).</li></ul><h3>Example Code (in Python)</h3><p>Here’s a Python code snippet using the scikit-optimize library:</p><pre>from skopt import gp_minimize<br>from skopt.space import Real<br>import numpy as np<br><br># Define the function to optimize<br>def objective(x):<br>    return np.sin(3 * x[0]) + x[0]**2 - 0.7 * x[0]<br><br># Define the search space<br>space = [Real(0, 2, name=&#39;x&#39;)]<br><br># Run Bayesian optimization<br>result = gp_minimize(objective, space, n_calls=10, random_state=42)<br><br>print(f&quot;Best x: {result.x[0]:.4f}&quot;)<br>print(f&quot;Best f(x): {result.fun:.4f}&quot;)</pre><p><strong>Optimization policy</strong></p><p>backtesting.py allows you to specify an optimization rule based on the maximization of a value that is reported by the backtest results, as in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*rm6TBFV7b_YRrr72tLfcGQ.png" /><figcaption>Backtest results: “margin calls” row and “Equity Final” are the fields to be maximized</figcaption></figure><p>The strategy in question is based on an approach without a true stop-loss, where the stop is interpreted as liquidation. A trade that fails tends to remain open for a long period, potentially blocking the bot. To avoid this situation, I prioritized maximizing equity and minimizing margin calls in the backtest. For example, if I achieve a 200% return over 3 years with margin calls and a 150% return without margin calls, I would prefer the latter result. This is because, although less profitable in absolute terms, it indicates that the strategy parameters avoided liquidation and allowed the bot to remain operational.</p><p>In the first case, despite the higher return, the backtest suggests that the strategy parameters failed to prevent liquidation in the past, implying that the bot may have been stuck for extended periods. This configuration may not be robust under conditions of volatility similar to those of the last 3 years for DOGE, potentially posing significant risks in the future.</p><p>In summary, it is crucial that the strategy effectively manages volatility and avoids liquidation scenarios that would immobilize the bot. The goal is to find a configuration that, while potentially less profitable in terms of return, demonstrates greater resilience and adaptability to market conditions.</p><pre>    constraint= lambda x: (x.bo_amount &lt; x.so_amount * 2/3) and<br>      x.bo_amount + sum([x.so_amount * pow(x.so_volume_scale,(a - 1)) for a in range(1,x.so_count+1)]) &lt;= available_cash * cash_multiplier /margin,<br>    maximize=lambda x: x[&#39;Equity Final [$]&#39;] / ( 1 + x[&#39;margin calls&#39;]),<br>    method=&#39;skopt&#39;,<br>    max_tries=500,</pre><p>The optimization function is based on the ratio between equity and margin calls, ideally aiming for zero margin calls. Indeed, for both DOGE and XMR, the optimization process identified suitable configurations.</p><p>Customization: The “margin calls” field in backtesting.py results does not exist by default. Therefore, I had to modify the Python module to ensure this value was included in the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*fke3Ca4zeTt6T9s6RGqriA.png" /><figcaption>End phase of optimization</figcaption></figure><p><strong>Results</strong></p><p>The optimization made it possible to obtain excellent results for both DOGEUSDT and the decorrelated token trade is negligible and even above all even if it were not, it still happens at different times and therefore the bot has always remained operational.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doxxrslsHIKhsuWQSoTQzQ.png" /><figcaption>equity line of strategy with DOGE, the red line above show just a little period of inactivity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8Kkwv__4-vXfbS6Tghbrg.png" /><figcaption>equity line of strategy with XMR, the red line above the equity show just a little period of inactivity that is different from the picture above related to DOGE token.</figcaption></figure><p><strong>Bot Freqtrade</strong></p><p>The implementation for Freqtrade is the most interesting as it allows trading multiple assets simultaneously, thereby completing the strategy with diversified pairs of decorrelated assets.</p><p>Each asset will have its own configuration generated through the optimization process explained earlier, and although this is somewhat unusual for Freqtrade, there is the advantage of fine-tuning parameters for each token.</p><p>The parameter values are defined in a dictionary for each token. This allows extracting the pair within each callback and using specific settings accordingly.</p><pre>    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -&gt; DataFrame:<br><br>      pair = metadata[&quot;pair&quot;]<br><br>      if pair not in self.custom_info:<br>        self.custom_info[pair] = [&#39;&#39;]<br><br>      [upperband, middleband, lowerband] = ta.BBANDS(dataframe[&quot;close&quot;], self.settings[pair][&quot;bb_len&quot;], self.settings[pair][&quot;bb_mul&quot;], self.settings[pair][&quot;bb_mul&quot;], matype=ta.MA_Type.EMA)<br>      dataframe[f&quot;{pair}-bb_upper&quot;] = upperband<br>      dataframe[f&quot;{pair}-bb_middle&quot;] = middleband<br>      dataframe[f&quot;{pair}-bb_lower&quot;] = lowerband<br>      return dataframe</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*npOFGsX3MWPzw4MJLOTt9g.png" /><figcaption>Dict of token settings</figcaption></figure><p>The backtest performed with DOGEUSDT reports the following results:</p><pre>freqtrade backtesting - strategy DecoBBDCA - config user_data/configs/config.DecoBBDCA.json - timeframe 5m - fee 0.0003 - timerange=20210602- - export signals - pairs DOGE/USDT:USDT</pre><pre>=================== SUMMARY METRICS ====================<br>| Metric                      | Value                  |<br>|-----------------------------+------------------------|<br>| Backtesting from            | 2021-06-02 10:40:00    |<br>| Backtesting to              | 2024-06-09 14:10:00    |<br>| Max open trades             | 1                      |<br>|                             |                        |<br>| Total/Daily Avg Trades      | 1426 / 1.29            |<br>| Starting balance            | 500 USDT               |<br>| Final balance               | 2290.988 USDT          |<br>| Absolute profit             | 1790.988 USDT          |<br>| Total profit %              | 358.20%                |<br>| CAGR %                      | 65.48%                 |<br>| Sortino                     | 0.36                   |<br>| Sharpe                      | 6.02                   |<br>| Calmar                      | 89.53                  |<br>| Profit factor               | 11.49                  |<br>| Expectancy (Ratio)          | 1.26 (0.01)            |<br>| Avg. daily profit %         | 0.32%                  |<br>| Avg. stake amount           | 71.283 USDT            |<br>| Total trade volume          | 101649.732 USDT        |<br>|                             |                        |<br>| Long / Short                | 742 / 684              |<br>| Total profit Long %         | 172.41%                |<br>| Total profit Short %        | 185.78%                |<br>| Absolute profit Long        | 862.069 USDT           |<br>| Absolute profit Short       | 928.92 USDT            |<br>|                             |                        |<br>| Best Pair                   | DOGE/USDT:USDT 358.20% |<br>| Worst Pair                  | DOGE/USDT:USDT 358.20% |<br>| Best trade                  | DOGE/USDT:USDT 18.28%  |<br>| Worst trade                 | DOGE/USDT:USDT -38.93% |<br>| Best day                    | 44.003 USDT            |<br>| Worst day                   | -170.587 USDT          |<br>| Days win/draw/lose          | 684 / 417 / 2          |<br>| Avg. Duration Winners       | 10:16:00               |<br>| Avg. Duration Loser         | 44 days, 0:05:00       |<br>| Max Consecutive Wins / Loss | 837 / 1                |<br>| Rejected Entry signals      | 0                      |<br>| Entry/Exit Timeouts         | 0 / 0                  |<br>|                             |                        |<br>| Min balance                 | 500.775 USDT           |<br>| Max balance                 | 2461.576 USDT          |<br>| Max % of account underwater | 6.93%                  |<br>| Absolute Drawdown (Account) | 6.93%                  |<br>| Absolute Drawdown           | 170.587 USDT           |<br>| Drawdown high               | 1961.576 USDT          |<br>| Drawdown low                | 1790.988 USDT          |<br>| Drawdown Start              | 2024-04-12 07:35:00    |<br>| Drawdown End                | 2024-06-09 14:10:00    |<br>| Market change               | -65.48%                |<br>========================================================<br><br>Backtested 2021-06-02 10:40:00 -&gt; 2024-06-09 14:10:00 | Max open trades : 1<br>================================================================ STRATEGY SUMMARY ===============================================================<br>|   Strategy |   Entries |   Avg Profit % |   Tot Profit USDT |   Tot Profit % |   Avg Duration |   Win  Draw  Loss  Win% |            Drawdown |<br>|------------+-----------+----------------+-------------------+----------------+----------------+-------------------------+---------------------|<br>|  DecoBBDCA |      1426 |           1.80 |          1790.988 |         358.20 |       11:44:00 |  1424     0     2  99.9 | 170.587 USDT  6.93% |<br>=================================================================================================================================================</pre><p><strong>Bot TradingView</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQsOelcovDAwFuNo-5lpnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q8Qyz9v_Qts6u5zyRAzXw.png" /></figure><p><strong>Live results</strong></p><p>The strategy is running by TradingView connected to the Bybit testnet. Below is the screenshot of the results. In this case the connection to bybit is realized using ByBit web-hook, therefore the strategy by pinescript activate an alert that place an order sending a mesage to bybit webhook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXBSXtjP3gCwZAlM2Zg1mg.png" /></figure><p>Furthermore, the strategy is running live on ByBit’s real account by Freqtrade using two decorrelated assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dm-MfNeMIkSpUUVNBIjNyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*WZFpRHWygilJhG9opEHZCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9Qr7Iy8YsHOdoONqaxxaw.png" /></figure><p><strong>Conclusions</strong></p><p>This work highlights that it is possible to develop strategies that are compatible with both TradingView and Freqtrade, provided that the constraints imposed by the tools used are carefully considered. Currently, the bot on Freqtrade is operating live and is meeting the target of 10% monthly profit. However, it is still early to draw definitive conclusions in this regard. The next step is to apply the process to multiple tokens so that the bot can open more trades and become more profitable.</p><p><strong>And the what happen after five months ?</strong></p><p>At the end I miss the target of 10% per month but…<br>The bot was improved, now It handle 4 tokens as 2 pairs of decorrelated tokens and also money management was improved by handling compound interest. <br>The whole performance is near 30%, about 6% per month. Market was strange in the latest months and the bot reacts very well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DP0lp0j4vWYK31WlWMaViA.png" /><figcaption>Equity line from beginning</figcaption></figure><p>I released a <a href="https://www.youtube.com/watch?v=7ObVTf3fIUo&amp;t=1446s">video</a> (in Italian language) were I discuss about the freqtrade implementation. The bot now is operating as master trader on bybit and is available for copy trading. Below the link.</p><p><strong>References</strong></p><p><a href="https://www.freqtrade.io/en/stable/"><em>Freqtrade</em></a><em><br></em><a href="https://www.tradingview.com/"><em>Tradingview</em></a><em><br></em><a href="https://kernc.github.io/backtesting.py/"><em>Backtesting.py</em></a><em><br></em><a href="https://scipy.org/"><em>Bayesian optimization</em></a><em><br></em><a href="https://youtu.be/oCX2yCneehM"><em>Video Part One (Italiano)</em></a><em><br></em><a href="https://www.youtube.com/watch?v=7ObVTf3fIUo&amp;t=1446s"><em>Video Part Two (Italiano)</em></a><em><br></em><a href="https://youtube.com/@arrabitbot?si=HhAdkPigICMl2ztL"><em>TradingBot con Ale (My Youtube channel)</em></a><em><br></em><a href="https://i.bybit.com/c8qabZ6?action=inviteToCopy"><em>Copy trading of this bot</em></a><em> (expired)<br></em><a href="https://i.bybit.com/ab1VZJeT?action=inviteToCopy"><em>Copy trading new link</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355c64ef0bc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gann Fan and Gann Square for TradingView]]></title>
            <link>https://medium.com/@arrabitoster/gann-fan-and-gann-square-for-tradingview-e01a885188ae?source=rss-bca388a41cd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e01a885188ae</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[gann]]></category>
            <category><![CDATA[indicators]]></category>
            <category><![CDATA[tradingview]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[TradingBot con Ale]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 15:50:54 GMT</pubDate>
            <atom:updated>2024-04-04T08:03:23.200Z</atom:updated>
            <content:encoded><![CDATA[<p>This article describe four TradingView indicators:</p><ul><li><em>Gann Fan</em></li><li><em>Gann Fan Sq9</em></li><li><em>Gann Square</em></li><li><em>Gann Square Sq9</em></li></ul><p>that help to perform market analysis with Gann’s techniques.</p><p>Legendary trader W.D. Gann illuminated the cyclical nature of financial markets, revealing their adherence to predictable patterns rooted in geometry, astronomy, and numerology. With his own trading results as evidence, Gann showcased the efficacy of these principles in uncovering market dynamics, including breakouts, reversals, and crucial price levels acting as support and resistance.</p><p>For who don’t know the theory and technique developed by Gann I suggest to look at the rich documentation and articles present on the web.</p><p>Before start I tell you something about me, I’m a software engineer and a trader. In the latest three years I dedicated my competence on trading system, bot and tools. I develop these tools with the collaboration of Andrea Prestana that is a trader and most of all an expert of the Gann theory. Ha handle a telegram community where it weekly shared market analysis. <a href="https://www.ganntrading.it/">Here a link of its internet site.</a></p><p><strong>TradingView Indicators</strong></p><h4><strong><em>Gann Fan</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K25NA-EFfxKi3vbCCQ5sxg.png" /></figure><p>Draw a positive or negative angles: x2, x4,x8 and Div2, Div4, Div8.<br>The main angle is X1 and is the most important. The angle is 45 degree therefore the relationship between time and price is one to one. <br>The other angles are obtained by multiplying or dividing the ratio between price and time.</p><h4>Sq9 Angles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRnBWZt2e60HvQTcXZYjIg.png" /></figure><p>While Gann base tools have a linear relationship between price and time as for one unit of time the market will rise (or fall) by one unit of price, the Square of 9 is<strong> </strong>a method which squares price and time. It’s is a grid that consists of a sequence of numbers arranged in a spiral pattern and get its name as if you draw a square starting from 1 at the center and turning around clockwise, the 9 represent the completion of first square. Sq9 relation could better represent market price relation with time. Traders use the Square of Nine to identify potential support and resistance levels, as well as to predict future price movements based on geometric relationships between numbers.</p><p><strong>Gann Square and Gann Square Sq9 (Gann Box)</strong></p><p>Gann Square, also known as the Gann Box, stands as a cornerstone of technical analysis, offering traders a powerful tool to decipher market movements and anticipate future price action. Built upon primary angles, notably the 45-degree (1x1 angle) ascending from the origin to the top-right corner and its corresponding negative angle descending from the top-right to the bottom-left corner, Gann Square epitomizes precision and foresight in chart analysis.</p><p><strong>Unveiling Points of Setup</strong></p><p>Central to Gann Square’s functionality is the identification of points of setup. These critical junctures mark significant highs or lows in price movements, serving as pivotal reference points for traders seeking to navigate market shifts and capitalize on emerging opportunities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*KJjHL7ucN1P2kPAYBMhNaw.png" /><figcaption>Square using Calendar Days</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ClSWdxd5TgcTr1bOR4_rKA.png" /><figcaption>Square with trading days (bars)</figcaption></figure><p><strong>Common features and settings</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*sv14KoRNyHuTXZUi-2e3hw.png" /><figcaption>Settings tab of the indicator placed on TradingView layout</figcaption></figure><ul><li>Scale and factor: allows to adapt angles and squares to any asset;</li><li>Automatic price placement: the indicator look at the trend and decide autonomously if angle starts from candle low or high;</li><li>Manual price placement: it’s possible to disable automatic placement and specify a start price;</li><li>Angle extension to present: draw angle until last available bar;</li><li>Extension to future: draw angle and square in the future after the latest available bar ( actual TradingView limit is 500 bars in the future );</li><li>Multiple timeframe are supported ( more details below);</li><li>Trading days: time is considered in number of bars, for example the ticker AAPL usually has 5 daily bars per week;</li><li>Calendar: time is considered in number of days, for example the ticker AAPL usually has 7 days per week;</li><li>Future bars: It’s possible to draw until 500 bars after the latest ( TradingView bound);</li><li>Square over bound handling (picture below);</li><li>Time based on trading days or calendar (more details below).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8SINqxJxSJW1_JM48z1gg.png" /><figcaption>handle TradingView bounds of 500 bars in the future</figcaption></figure><h3>Calendar and trading days</h3><p>A lot of effort was spent to realize a precise relationship between time and price, as angles price arise with time and could increase proportionally after any bar of after any day. The best of this two option is related to the type of instrument used.<br>For example, with Trading Days an instrument ticker at market from Monday to Friday, could have 5 bars, and following week, again on Monday we have six bars, in this case there is a match between candle on the chart and the trading days time so the angle arise in a linear way. Instead using Calendar option, with the same instrument of previous example, from Monday to Monday we have 7 days and 6 candles on the chart, therefor the algorithm take care that from Friday to Monday is one candle but 3 days and angle arise proportionally with days. In this case on the chart you can observe a little step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*2jzfKDTOAwAtNI-eOcFI8g.png" /><figcaption>Calendar and angles step</figcaption></figure><p><strong>Timeframe independence</strong></p><p>In Gann analysis, the correlation between angles and time periods is inherently cyclical, where each degree corresponds to approximately one day, and a full circle of 360 degrees symbolizes a year. This timeless relationship allows Gann indicators to transcend individual timeframes, ensuring consistency while preserving the critical balance between time and price dynamics.</p><p>Gann indicators operate seamlessly across multiple timeframes, yet they remain steadfastly anchored to the daily timeframe as the primary reference point. This deliberate choice maintains the integrity of the time-price relationship, essential for accurate analysis and interpretation.</p><p><strong>Preserving Proportion Amidst Time Shifts</strong></p><p>When an angle intersects a pivot point during a timeframe transition, the Gann indicator upholds its proportional integrity without compromise. Whether examining daily, weekly, or monthly intervals, the indicator seamlessly aligns with pivotal price levels, ensuring continuity and precision in analysis.</p><p><strong>Illustrating Consistency in Practice</strong></p><p>Visualize the power of timeframe independence through a single Gann fan spanning both daily and weekly intervals. Witness how each angle touches the same pivotal point, meticulously maintaining proportionality across varying timeframes, as depicted in the accompanying illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nWvYVP8FT3Ulv7O0x2PBVQ.png" /><figcaption>Angles proportion remains consistent changing time frame.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDIRLOSD7TQxlq8oziMkSw.png" /><figcaption>Gann square on 1h timeframe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yefmGcaforVp4RKEAxmcOA.png" /><figcaption>Gann square 1H and 30&#39; timeframe</figcaption></figure><p><strong>Issues</strong></p><p>Some issues are related to Tradingview limit about data availability, for example candle in the past are limited and depend of the type of TV subscription. <br>Another limit is about TradingView drawing in the past capabilities as with latest release the bound is of 10000 candles in the past. There are limit to paint in the future, the maximum allowed is of 500 bars.</p><p><strong>Improvement</strong></p><p>Next planned releases include full intraday support and new Gann indicators.</p><p><strong>How to get this indicators</strong></p><p>Indicator are privately available. <br><a href="https://it.tradingview.com/u/Strambatax/">You can contact me on TradingView</a> <br>or you can buy the indicator in bundle <a href="https://www.ganntrading.it/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e01a885188ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ByBit TradingView WebHook e il connector non serve più!]]></title>
            <link>https://medium.com/@arrabitoster/bybit-tradingview-webhook-e-il-connector-non-serve-pi%C3%B9-2f51e0b346d3?source=rss-bca388a41cd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f51e0b346d3</guid>
            <category><![CDATA[bybit-webhook]]></category>
            <category><![CDATA[tradingview]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[bybit]]></category>
            <category><![CDATA[placeholder]]></category>
            <dc:creator><![CDATA[TradingBot con Ale]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 09:39:25 GMT</pubDate>
            <atom:updated>2023-08-05T09:58:30.461Z</atom:updated>
            <content:encoded><![CDATA[<p>ByBit da poco ha messo a disposizione un proprio webhook per ricevere messaggi direttamente da TradingView. In precedenza era necessario usare un intermediario, perché Bybit da sempre mette a disposizione un set di API che consente ad applicazioni di terze parti di interagire con l’exchange stesso. Quindi ci sono svariati servizi di rete, chiamati connector, che possono ricevere un messaggio da TradingView ed aprire trade su Bybit. Ma ora Bybit ha il suo connector, non è più necessario utilizzare servizi di terze parti.</p><p><strong>Questa funzionalità è presente anche sulla testnet di ByBit e quindi è possibile azionare il proprio Bot senza l’utilizzo di denaro reale.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*0eCIomwsVDI8yAzgbt6RGA.png" /></figure><p>il webhook è un indirizzo URL nel dominio di ByBit che consente di inviare un messaggio all’exchange. Il messaggio può essere inviato esclusivamente da TradingView.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMxnIKTnMT9Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMxnIKTnMT9Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMxnIKTnMT9Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/444e208979b2a32fc94f9d0c01694a08/href">https://medium.com/media/444e208979b2a32fc94f9d0c01694a08/href</a></iframe><h3>WebHook: Messaggio</h3><pre>{<br>  &quot;symbol&quot;:&quot;{{ticker}}&quot;,<br>  &quot;side&quot;:&quot;{{strategy.order.action}}&quot;,<br>  &quot;qty&quot;:&quot;{{strategy.order.contracts}}&quot;,<br>  &quot;price&quot;:&quot;{{close}}&quot;,<br>  &quot;trigger_time&quot;:&quot;{{timenow}}&quot;,<br>  &quot;strategy_id&quot;:&quot;a2fca081-b378-416b-a899-47fd5a0dc2a0&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*yNs43OxsxdUkcp3IpgzNLg.png" /><figcaption>Configurazione dell’alert su TradingView</figcaption></figure><p>Come si può vedere dal JSON qui sopra, il messaggio può fornire indicazioni circa il simbolo, il tipo di operazione (long/short), la quantità, il prezzo, etc.<br>L’alert di TradingView dovrà inviare questo messaggio a Bybit per piazzare un ordine.</p><p>Il Messaggio può essere formattato tramite pinescript, e quindi i campi JSON possono essere valorizzati da codice ma è anche possibile utilizzare il messaggio preconfezionato, così come mostrato qui sopra, perché le parole tra doppie graffe, ad esempio {{ticker}} sono dei <a href="https://www.tradingcode.net/tradingview/standard-placeholders-explained/"><strong>placeholder</strong></a> di TradingView e quando l’alert verrà emesso, i campi tra {{}} verranno valorizzati con gli opportuni valori.</p><h3>Quantità di contratti</h3><p>Per valorizzare il campo quantità è possibile specificare un valore, che sia fisso o dinamico, oppure impostato utilizzando <a href="https://it.tradingview.com/pine-script-reference/v5/"><strong>pinescript</strong></a>, deve essere compatibile col proprio money management e col capitale specificato nella strategia<strong>. </strong>A questo scopo, il <a href="https://www.tradingcode.net/tradingview/standard-placeholders-explained/"><strong>placeholder</strong></a><strong> </strong>{{strategy.order.contracts}} risulta molto comodo ma è necessario che le proprietà della strategia circa il money management siano configurate correttamente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*fckKcksD7_yGsjY4cXCRAA.png" /><figcaption>Money management</figcaption></figure><p>Faccio un esempio per spiegarmi meglio: Ho un capitale di 7,000$ e voglio effettuare ordini per una dimensione pari al 10% del capitale, cioè di 700$, a questo punto quando entra in funzione l’alert, il numero di contratti riportati dal placeholder per valorizzare la quantità sarà pari alla dimensione dell’ordine diviso il prezzo.<br>Faccio una digressione, specificando una dimensione superiore al capitale, è anche possibile operare in leva. Questa è un’operazione molto rischiosa, ma su molti exchange, come su ByBit, è possibile usare alcune precauzioni come l’utilizzo di un subaccount in modo tale che una eventuale liquidazione sia limitata al subaccount stesso.</p><h3>DISCLAIMER</h3><p>Questo articolo è solo a scopo educativo. Non sono in alcun modo responsabile di cattive impostazioni, strategie e possibili perdite o guadagni di denaro che ne conseguono! Tutto quanto espresso qui è la mia opinione e non un consiglio di investimento. Investire o fare trading in criptovalute o qualsiasi asset finanziario comporta un alto grado di rischio e dovrebbe essere preso in considerazione solo da persone che possono permettersi di sostenere una perdita dell’intero investimento. Si prega di fare le proprie ricerche o consultare un consulente finanziario prima di prendere qualsiasi decisione finanziaria.</p><p><a href="https://www.bybithelp.com/en-US/s/article/How-to-Use-and-Setup-Webhook-Signal-Trading-on-Bybit">https://www.bybithelp.com/en-US/s/article/How-to-Use-and-Setup-Webhook-Signal-Trading-on-Bybit</a></p><p><a href="https://www.tradingcode.net/tradingview/standard-placeholders-explained/">https://www.tradingcode.net/tradingview/standard-placeholders-explained/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f51e0b346d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Come collegare una strategia di TradingView all’Exchange]]></title>
            <link>https://medium.com/@arrabitoster/come-collegare-una-strategia-di-tradingview-allexchange-74477f144f12?source=rss-bca388a41cd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/74477f144f12</guid>
            <category><![CDATA[trading-strategy]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[bitget]]></category>
            <category><![CDATA[tradingview]]></category>
            <category><![CDATA[bybit]]></category>
            <dc:creator><![CDATA[TradingBot con Ale]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 17:27:59 GMT</pubDate>
            <atom:updated>2023-06-18T17:27:59.625Z</atom:updated>
            <content:encoded><![CDATA[<p>TradingView fornisce la possibilità di collegamento con diversi broker, ma questo è perlopiù limitato ai mercati tradizionali e molti Exchange che trattano cripto valute non sono supportati.<br>Per poter utilizzare una strategia codificata in Pinescript e far si che a fronte di una istruzione di Entry venga piazzato l’ordine serve un intermediario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*qxG8GF3Nnv9zsXNFZaOFDQ.png" /></figure><p>Faccio un passo indietro, quando si codifica una strategia, TradingView fornisce il backtest di questa strategia mostrando i trade svolti nel passato. Quando per la stessa strategia viene creato un alert, come mostrato di seguito, la strategia in tempo reale, nel momento in cui si verificano le condizioni di ingresso emetterà l’alert e questo consentirà di piazzare l’ordine sull’Exchange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIqDzkAs3UQDN1CMO_vU7w.png" /><figcaption>creazione di un alert</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUZVIKa0oIAI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUZVIKa0oIAI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUZVIKa0oIAI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b884a558cdfe8a4d0c248f01645f1424/href">https://medium.com/media/b884a558cdfe8a4d0c248f01645f1424/href</a></iframe><p>Nel video (v1) mostro come collegare una strategia a ByBit effettuando tutti i passaggi del caso.</p><h3>Che strumenti servono…</h3><p>1 — Una strategia sviluppata in Pinescript o semplicemente un alert;</p><p>2 — L’API key dell’ exchange con i permessi necessari a piazzare un trade (vedi video v1);</p><p>3 — Un connector: ovvero un intermediario che fa da passacarte tra TradingView e l’Exchange (video v1 e v2).</p><p>Mentre i primi due punti sono abbastanza scontati, il ruolo del connector lo è un po’ meno, provo a spiegare la sua utilità.<br>Un Exchange, in genere, mette a disposizione una interfaccia per poter dialogare con lui, oltre a quindi quella canonica che può essere web o un’applicazione mobile. Questa interfaccia si chiama API (Application program interface) e consente ad altre applicazioni di dialogare con l’exchange.<br>Un connector è uno strumento che riceve un comando di TradingView e poi, utilizzando le API messe a disposizione da uno specifico Exchange, pizza l’ordine, in questo modo sarà del tutto trasparente a TradingView e all’utente se ad esempio configuro il connector per parlare con ByBit piuttosto che con Bitget.<br>Il connector viene invocato tramite un EndPoint, cioè un indirizzo di rete http, che dovrà essere messo nell’alert di TradingView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*McQiqgZuueOvj0ZjQBP4fg.png" /><figcaption>URL Webhook con l’indirizzo del connector</figcaption></figure><h3>Strategia e messaggio dell’ alert</h3><p>Nel codice Pinescript è possibile piazzare l’ordine tramite l’istruzione “entry” ed chiudere il trade con “exit”, queste due funzioni hanno un parametro (alert_message) che permette di specificare cosa inviare al webhook del connector.</p><pre>strategy.entry(&quot;long_entry&quot;, strategy.long, when=entry_long, comment=&quot;lbo&quot;, alert_message=cmd_connector)</pre><p>Il cosa inviare (payload) dipende dal connector. Ad esempio Tv-Hub, supporta una sintassi JSON abbastanza sofisticata, che permette di specificare diversi attributi per l’ordine, come il ticker, la direzione long o short, la size (percentuale o assoluta) e addirittura se l’ordine deve essere limite o a mercato.</p><pre>string cmd_connector = &#39;{&#39;&quot;pair&quot;:&quot;{0}&quot;,&quot;units&quot;:&#39;{{strategy.order.contracts}}&#39;,&quot;isBuy&quot;:true,&quot;unitsType&quot;:&quot;absolute&quot;,&quot;exchange&quot;:&quot;Bybit&quot;,&quot;apiKey&quot;:&quot;xxxx&quot;,&quot;token&quot;:&quot;xxxxxxxxxxxxxxxx&quot;,&quot;isMarket&quot;:true,&quot;leverage&quot;:{1,number,#},&quot;marginType&quot;:&quot;CROSSED&quot;,&quot;closeCurrentPosition&quot;:true,&quot;cancelAllOrders&quot;:true&#39;}&#39;</pre><p>In questo modo la strategia stessa può formattare il comando che deve essere mandato al connector, e questo comando dato in pasto al parametro alert_message della funzione entry farà si che l’alert invierà all’endpoint del connector il comando stesso. Il connector sulla base di questo piazzerà il trade sull’Exchange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*le25azOZjCeXCQ-D9q-kXA.png" /><figcaption>Il placeholder {{strategy.order.alert_message}}</figcaption></figure><p>La figura qui sopra mostra come configurare l’alert per fare in modo che il comando messo nel parametro della funzione entry finisca nel messaggio dell’ alert.</p><h3>Soluzioni più semplici</h3><p>Esistono connector che consentono di impostare una strategia, fornendo il token, la direzione long o short, i livelli di ingresso, take profit, trailing, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OrdT7jGcnIK0Buil9Rcqw.png" /></figure><p>Il connector rilascia un semplice token, che non è un comando vero e proprio ma quando TradingView genera l’alert il token sarà il messaggio per il connector e quest’ultimo saprà già cosa fare: che cripto tradare, long o short, etc.<br>A fronte di una estrema semplicità c’è lo svantaggio di una minor configurabilità, per esempio se volessi mettere uno take profit parziale ad un livello che non è noto a priori, magari basato su un multiplo dell’ATR, sarebbe un problema specificare questa azione tramite la configurazione del connector.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6NDE1e3ZFRo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6NDE1e3ZFRo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6NDE1e3ZFRo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eff15efca7552c3cc1711540be9c78d9/href">https://medium.com/media/eff15efca7552c3cc1711540be9c78d9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74477f144f12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>