<?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 Jaden Duxfield on Medium]]></title>
        <description><![CDATA[Stories by Jaden Duxfield on Medium]]></description>
        <link>https://medium.com/@jadendux?source=rss-1b2d0aca2876------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*alcdVEf4L39bIwDgR8He8g.jpeg</url>
            <title>Stories by Jaden Duxfield on Medium</title>
            <link>https://medium.com/@jadendux?source=rss-1b2d0aca2876------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:23:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jadendux/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[Context Compression with Local LLMs: Early Results and Trade-offs]]></title>
            <link>https://medium.com/@jadendux/context-compression-with-local-llms-early-results-and-trade-offs-dfba73f022a6?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfba73f022a6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[qwen-3]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 01:07:59 GMT</pubDate>
            <atom:updated>2026-07-27T01:07:59.484Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been experimenting with using local models as context compressors to cut token usage in long conversations while trying to keep comprehension intact. The idea is simple: instead of feeding the full history to the main model, run a smaller compressor first to produce a shorter summary or rewritten context.</p><p>Here’s what the first round of tests showed.</p><h3>The Setup</h3><p>I ran six questions against a fixed long context of financial facts and figures. The baseline (no_compression) used the raw context. The other runs used different local models to compress the same context before answering. I tracked three things:</p><ul><li><strong>Score</strong> — how well the final answer matched the expected information (0–10 scale)</li><li><strong>Tokens</strong> — context size after compression</li><li><strong>Time</strong> — wall time for the compression step</li></ul><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CbN95UXOij-W-ToCfsCYw.png" /><figcaption>Average Score, Time and Tokens used each questio</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*P5rdZiMqAncxL609ZmKtJQ.png" /></figure><p><strong>Token savings are real, but comprehension is fragile.</strong><br> Even the best compressor (qwen3:14b) only kept scores close to baseline on the first two questions. After that, performance collapsed for most models. This suggests current local models are decent at surface-level summarization but struggle to preserve the specific details needed for later questions.</p><p><strong>Larger models within the local set did better early on.</strong><br> qwen3:14b was the only one that scored a perfect 10 on Question 1 and 9 on Question 2 while still cutting ~300–500 tokens. The 8B and 4B class models lost critical information much faster.</p><p><strong>Inference time is the hidden cost.</strong><br> Compression added 5–30 seconds per query depending on the model. For interactive chat this latency quickly becomes noticeable, especially with the smaller quantized models that took 70+ seconds on some runs.</p><p><strong>Later questions expose the weakness.</strong><br> Questions 3–6 consistently showed the biggest score drops across all compressors. This points to a common failure mode: the models are dropping or distorting information that only becomes relevant several turns later.</p><h3>Practical Takeaways So Far</h3><ul><li>If your priority is maximum token reduction with acceptable quality loss, qwen3:14b is currently the strongest candidate in this set.</li><li>For anything that needs high fidelity across a long conversation, the current approach is still too lossy.</li><li>The sweet spot probably lies between “raw context” and “aggressive compression.” Techniques like selective retrieval or multi-pass compression might be worth exploring next.</li></ul><p>I’ll be running a second round with better prompting strategies and a few more models. If you’re doing similar experiments, I’d be interested in hearing what compression approaches have worked for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfba73f022a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New Probability Distribution strategy in the forex market]]></title>
            <link>https://medium.com/@jadendux/new-probability-distribution-strategy-in-the-forex-market-588ae76d7382?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/588ae76d7382</guid>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 12:03:15 GMT</pubDate>
            <atom:updated>2024-04-29T12:03:15.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strategy theory</h3><p>Substantial price fluctuations often signal significant market movements, which may suggest a forthcoming retracement or reversal. By leveraging the distribution curve, we can identify large moves by examining the quartiles. When we observe a substantial deviation from typical returns, followed by a return approximately half the size of the initial move, such candlestick patterns may indicate a potential reversal or retracement.</p><p>When constructing a trading strategy, three key factors are essential: trend recognition, entry signals, and exit/invalidation criteria. This article will detail the components used in this strategy, along with the statistical analysis of historical data for GBPUSD in the year 2023.</p><h3>Probability distribution</h3><p>Probability distribution curves are extensively used in finance due to their ability to model and understand the uncertainty inherent in financial markets in a visual way. These curves, often depicted as histograms or kernel density estimates (KDEs), provide insights into the likelihood of various outcomes occurring within a given financial context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V85PjMlQixvrdcpUI0cDpw.png" /><figcaption>KDE and Histogram plot</figcaption></figure><p>The red lines on the plot delineate the upper and lower quartiles, indicating where 50% of the returns fall within the larger distribution. Returns between these lines are considered typical, while those outside may be deemed as outliers or unusual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfYR1IRhtBEELF-S2cNaIw.png" /><figcaption>Signals from October to November 2023</figcaption></figure><p>The signals exhibit a propensity for identifying market tops and bottoms during certain movements, suggesting their utility as indicators for initiating trends. Now, the focus shifts towards devising methods to detect signs of trend exhaustion.</p><h4>Volume Weighted Average Price (VWAP)</h4><p>Utilizing the weekly anchored VWAP is pivotal in assessing whether prices are trading at a premium or discount. This approach enables seizing opportunities presented by mid-week reversals and price shifts triggered by news releases later in the week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XygrsWiYdBF80guv3LFoVA.png" /><figcaption>Signals with VWAP from October to November 2023</figcaption></figure><p>Observing the chart, it becomes evident that when the price is trading below the VWAP, indicating a discount, and a signal emerges to move higher, both factors can serve as confirming indicators for entering a trade.</p><h3>Exiting position</h3><p>This aspect of a strategy holds utmost importance, as maintaining profitable positions for as long as possible is essential for maximizing trade efficiency. A widely adopted technique in algorithmic trading is to employ the Relative Strength Index (RSI) as an exit indicator. This method ensures that trade closure isn’t solely dictated by price fluctuations, enabling trades to evolve while guaranteeing eventual closure based on RSI signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Twhg_nMUGkC_pBsP8kbCUQ.png" /><figcaption>Green arrow is position opened and red arrow is position closed.</figcaption></figure><p>Considering the outlined conditions, the strategy appears robust overall. However, it’s crucial to address a scenario where a trade isn’t given a chance to close, potentially erasing profits from previous trades and incurring further losses. To mitigate this risk, an additional condition is necessary, namely a stop-loss mechanism based on both the VWAP and candlestick behavior.</p><p>For instance, if a short position is initiated and a bullish candle closes above both the entry price and the VWAP, or conversely for long positions, this condition triggers a stop-loss, safeguarding against adverse market movements while allowing open trades to remain active.</p><h3>Backtesting</h3><p>Python provides a straightforward backtesting process, enabling the compilation of statistics and rapid strategy optimization. Below is a code snippet demonstrating how the strategy was backtested over a DataFrame containing all the necessary signal columns:</p><pre>def backtesting(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    &#39;&#39;&#39;<br>    Longs: below vwap -&gt; PD signal<br>    Shorts: above vwawp -&gt;  PD signal<br>    Exit contions are either:<br>        1. price retraces to the mid point of the RSI<br>        2. close long if there is a bearish close below the vwap (in DD). Close short if there is a bullish close above vwap (in DD)&#39;&#39;&#39;<br><br>    results = pd.DataFrame(index=df.index, columns=[&#39;entry_price&#39;, &#39;exit_price&#39;, &#39;type&#39;, &#39;exit_date&#39;])<br>    position_open = False<br>    position_index = None<br>    for i in range(len(df)):<br>        close_price = df[&#39;close&#39;].iloc[i]t<br>        # open position<br>        if close_price &gt; df[&#39;vwap&#39;].iloc[i]:<br>            if  not position_open and df[&#39;signal&#39;].iloc[i] == 1:<br>                #open short position<br>                position_open=True<br>                results[&#39;entry_price&#39;].iloc[i]= close_price<br>                results[&#39;type&#39;].iloc[i] = &quot;short&quot;<br>                position_index = df.index[i]<br><br>        elif close_price &lt;  df[&#39;vwap&#39;].iloc[i]:<br>            if  not position_open and df[&#39;signal&#39;].iloc[i] == 2:<br>                #open long position<br>                position_open=True<br>                results[&#39;entry_price&#39;].iloc[i] = close_price<br>                results[&#39;type&#39;].iloc[i] = &quot;long&quot;<br>                position_index = df.index[i]<br>        # Close position<br>        if position_open :             <br>                #Close short<br>                if results[&#39;type&#39;].loc[position_index] == &quot;short&quot;:         <br>                    # stoploss being triggered<br>                    if (close_price &gt; results[&#39;entry_price&#39;].loc[position_index] and <br>                        df[&#39;trend&#39;].iloc[i] ==&#39;up_candle&#39; and<br>                        df[&#39;vwap&#39;].iloc[i] &lt; close_price ) :<br>                            position_open = False<br>                            results[&#39;exit_price&#39;].loc[position_index] = close_price<br>                            results[&#39;exit_date&#39;].loc[position_index] = df.index[i]<br>                            position_index = None<br>                            <br>                    elif df[&#39;exit&#39;].iloc[i] == 2:<br>                            # add data to the results df<br>                            position_open = False<br>                            results[&#39;exit_price&#39;].loc[position_index] = close_price<br>                            results[&#39;exit_date&#39;].loc[position_index] = df.index[i]<br>                            position_index = None<br>    <br>                <br>                #close long<br>                elif results[&#39;type&#39;].loc[position_index] == &quot;long&quot;:<br>                    # stoploss being triggered<br>                    if (close_price &lt; results[&#39;entry_price&#39;].loc[position_index] and <br>                        df[&#39;trend&#39;].iloc[i] ==&#39;down_candle&#39; and<br>                        df[&#39;vwap&#39;].iloc[i] &gt; close_price ):<br>                            # add data to the results df<br>                            position_open = False<br>                            results[&#39;exit_price&#39;].loc[position_index] = close_price  <br>                            results[&#39;exit_date&#39;].loc[position_index] = df.index[i]<br>                            position_index = None <br><br>                    # hits tp  <br>                    elif df[&#39;exit&#39;].iloc[i] == 1:<br>                            # add data to the results df<br>                            position_open = False<br>                            results[&#39;exit_price&#39;].loc[position_index] =close_price <br>                            results[&#39;exit_date&#39;].loc[position_index] = df.index[i]<br>                            position_index = None<br>    return results.dropna()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*NnEpPDZwluE6YPXlBiLXIw.png" /><figcaption>Trades entered from October to November</figcaption></figure><p>The bot’s results are already demonstrating promising outcomes, characterized by significant gains from winning trades and minimal losses. The function is now prepared to be applied to the entire dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRbtT0-m27HGsSBRZDQbCw.png" /><figcaption>Equity curve for this strategy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*0XxIqjmkUgEkc2ivOig6Tg.png" /><figcaption>Strategy statistics</figcaption></figure><p>The bot appears to have generated positive gains throughout the 2023 trading year, despite having a relatively low win rate. However, this is offset by the notable difference between the average size of winning trades and the average size of losing trades.</p><h3>Optimization</h3><p>Several variables can be fine-tuned to enhance results. For instance, adjusting the threshold on the probability distribution curve can reduce trade frequency, potentially improving accuracy. Similarly, modifying the RSI threshold for trade exits can prolong trade durations, potentially boosting returns per trade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2EPz1jxfK9irzXtq456rA.png" /><figcaption>Heatmaps for different factors (1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhHn3RMxCX4gnol00JJqzw.png" /><figcaption>Heatmaps of different factors (2)</figcaption></figure><p>Heatmaps offer a visual representation of how strategy parameters influence trading outcomes, providing insights into the optimal values for these variables. The Sharpe ratio serves as a critical metric for evaluating strategy effectiveness by quantifying risk-adjusted returns. Fluctuations in the Sharpe ratio in response to parameter changes underscore the sensitivity of the strategy to these variables, highlighting the importance of fine-tuning them for optimal performance. However the sharp ratio is still under 1 which makes this strategy not robust enough to consider it for live market conditions.</p><h3>Conclusion</h3><p>In conclusion, the trading strategy outlined in this article provides a solid foundation for capturing market opportunities and generating consistent returns. By leveraging probability distribution curves, trend recognition techniques, and robust exit criteria, traders can identify high-probability trade setups and manage risk effectively.</p><p>However, to further optimize and adapt the strategy to evolving market conditions, the integration of machine learning techniques offers a promising avenue for improvement. Machine learning algorithms, such as neural networks, random forests, and deep learning models, can analyze vast amounts of historical data to uncover complex patterns and relationships that may not be apparent to human traders.</p><p>Thank you for reading.</p><p>The code for this can be found at:<br><a href="https://github.com/MrPotatoHead-Dev/Probability-Distribution-FX-strategy">https://github.com/MrPotatoHead-Dev/Probability-Distribution-FX-strategy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=588ae76d7382" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive study on Weekly Open Gaps in the forex market (GBPUSD)]]></title>
            <link>https://medium.com/@jadendux/comprehensive-study-on-weekly-open-gaps-in-the-forex-market-gbpusd-4e23c1fdc367?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e23c1fdc367</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 18:50:54 GMT</pubDate>
            <atom:updated>2024-03-05T18:50:54.429Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comprehensive study on Weekly Gaps in the forex market (GBPUSD)</h3><h3>Introduction:</h3><p>The enigma of the weekly open gap has captivated traders for numerous years, its elusive nature defying easy explanation or prediction. Nonetheless, traders have recognized its potential and devised strategies centred around this phenomenon. In this comprehensive study, I aim to illuminate the impact of the weekly open gap on the weekly candle, providing an analysis using historical data and python to empower traders with a strategic edge in their pursuit of financial gain. By delving into the complexities surrounding market gaps, we seek to enhance your trading arsenal with actionable insights derived from a meticulous examination of the interplay between the weekly open gap and the broader financial landscape.</p><h3>Binning data</h3><p>When importing data into Python, the initial phase involves data cleaning to ensure accuracy and reliability. One crucial aspect is quantifying the gap sizes, allowing us to categorize values into distinct gap sizes, such as large, medium, or small. Leveraging the power of the pandas library in Python, this process is streamlined through the use of binning. By segmenting the gap values into predefined bins, we can easily discern patterns and trends within the data.</p><p>Here’s a code snippet showcasing the binning process:</p><pre>def QuantifyGapSize(df: pd.DataFrame) -&gt; None:<br><br>    # copy dataframe<br>    df_copy = df.copy()<br><br>    # 2 bins are used to switch between the two and have a better understanding of the counts<br>    bins = [0,5 , 10, 15, 20, 30, 40]<br>    new_bins = [0, 10, 20, 30]<br>    # extract values<br>    gaps_values = df_copy[&#39;gaps&#39;].values<br>    # add to a pandas series<br>    gaps_values = pd.Series(gaps_values)<br>    # bin results<br>    sorted_bins = pd.cut((gaps_values.abs()), new_bins)<br>    # count results<br>    count_bins =sorted_bins.value_counts()<br>    print(count_bins)<br>    # print a bar chart using pandas built in plot<br>    count_bins.plot(kind=&#39;bar&#39;, title=&quot;Gap size counter&quot;, xlabel=&quot;Bins (pips)&quot;, ylabel=&#39;Count&#39;, color=&#39;magenta&#39;, edgecolor=&#39;black&#39;, rot=0)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*yGFqshajyxDsq0N80dmcng.png" /><figcaption>Gap sizes in their appropriate bins #1</figcaption></figure><p>Inspecting the resulting bins, we may find that further synthesis is warranted. In this context, the bins can be refined to represent broader categories, such as 0–10, 10–20, and 20–30. This adjustment not only simplifies interpretation but also aids in the extraction of meaningful insights from the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*OJB8rhlCxfxdfWsuyqngyA.png" /><figcaption>Gap sizes in their appropriate bins #2</figcaption></figure><h3>Gaps influencing weekly trend</h3><p>Following the categorization of gap sizes into bins, the subsequent analysis aims to investigate whether the size of the gap influences the direction of the weekly candle’s closing. Specifically, the code is designed to determine if a downside gap correlates with a downward close and vice versa.</p><p>This function was created to evaluate the gap sizes and their influence on the weekly candle:</p><pre>def GapStats(df: pd.DataFrame, pip_value: int) -&gt; None:<br>    df_copy = df.copy()<br>    # create result lists<br>    res_bull_true = 0<br>    res_bull_false = 0<br>    res_bear_true = 0<br>    res_bear_false = 0<br>    large_gap_counter = 0<br>    choppy_day = 0<br>    trend_day = 0<br>    gaps = 0<br>    <br>    for i in range(1,len(df_copy)):<br>        <br>        if df_copy[&#39;gaps&#39;].iloc[i] &gt; pip_value:<br>            gaps += 1<br>            if df_copy[&#39;trend&#39;].iloc[i] ==2:<br>                res_bull_true += 1<br>            else:<br>                res_bull_false += 1<br>        elif df_copy[&#39;gaps&#39;].iloc[i] &lt; -pip_value:  <br>            gaps += 1<br>            if df_copy[&#39;trend&#39;].iloc[i] ==1:<br>                res_bear_true += 1<br>            else:<br>                res_bear_false += 1  <br>        # does a higher gap mean weekly chop or trend. i.e large wicks or large body<br>        if df_copy[&#39;gaps&#39;].iloc[i] &gt;= 20:<br>            large_gap_counter += 1<br>            if df_copy[&#39;top_wick&#39;].iloc[i] &gt; df_copy[&#39;body&#39;].iloc[i] and df_copy[&#39;bottom_wick&#39;].iloc[i] &gt; df_copy[&#39;body&#39;].iloc[i]:<br>                choppy_day += 1<br>            elif df_copy[&#39;top_wick&#39;].iloc[i]*1.5 &lt; df_copy[&#39;body&#39;].iloc[i] and df_copy[&#39;bottom_wick&#39;].iloc[i]*1.5 &lt; df_copy[&#39;body&#39;].iloc[i]:<br>                trend_day += 1<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*eYyhRZ6hy0JofbVMeXvNGg.png" /><figcaption>Gaps greater than 10pips</figcaption></figure><p>Looking at gaps greater than 10pips there is evidence that the weekly candle will close in the direction of the gap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*PhNkQPbigAkGRyznK9eGKg.png" /><figcaption>Gaps between 10–20 pips</figcaption></figure><p>If the gap is greater than 10 pips but less than 20 pips there is a higher chance that the weekly candle will close in its direction but if the gap is larger than 20 there seems to be no clear indication that the weekly candle will close in its direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*CVQ0MXziJrB3w6IdjgFABQ.png" /><figcaption>Gaps greater than 20pips</figcaption></figure><p>Shows there is near a 50/50 change for gaps greater than 20 to have an impact on the weekly closing price.</p><h3>Large gaps meaning on candle formation</h3><p>Recently, I’ve come across the idea that a substantial gap in weekly trading tends to signal a choppy market. To test this hypothesis and quantify choppiness, I defined a choppy week as one where price lacks a clear direction, oscillating around a specific point with weekly candles exhibiting large wicks, larger than the body. Conversely, I defined a trending week as having a body greater than 1.5 times each wick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*aAR0e-XKwOtlFU0OFm53Fw.png" /><figcaption>Gaps exceeding 15pips</figcaption></figure><p>Initially, I considered a large gap as anything exceeding 15 pips. However, upon analyzing the results, the data did not support the initial claim. Out of 33 weeks with gaps larger than 15 pips, only 20 were categorized as either choppy or trending. This indicates that some candles were not accounted for and may provide additional insights into the week’s market conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*nqJyV3VAPSbR75VCBuVyuQ.png" /><figcaption>Gaps exceeding 20pips</figcaption></figure><p>Even when I increased the gap size threshold to 20 pips, the results still showed a significant number of trending weeks compared to choppy ones. This suggests that the relationship between gap size and market choppiness might be more nuanced than initially assumed. It’s essential to consider other factors and variables in future analyses to develop a more comprehensive understanding of market dynamics.</p><h3>Conclusion</h3><p>In conclusion, the analysis of gap sizes and their impact on the closing direction of weekly candles has yielded noteworthy insights. Specifically, when examining gaps exceeding 10 pips, there is evidence to suggest a correlation between the size and direction of the gap and the subsequent weekly candle closing direction. Notably, instances of gaps greater than 10 pips tend to align with the closing direction of the weekly candle, indicating a potential predictive relationship.</p><p>These findings could have implications for trading strategies, suggesting that traders may benefit from considering the size and direction of weekly gaps when anticipating the closing direction of the weekly candle. However, it’s essential to note that market dynamics are multifaceted, and further analysis, including consideration of additional factors, is recommended to refine and validate these observations</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e23c1fdc367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove emotion from trading: Using Python to apply risk management strategies]]></title>
            <link>https://medium.com/@jadendux/remove-emotion-from-trading-using-python-to-apply-risk-management-strategies-90fb565e2f31?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/90fb565e2f31</guid>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 20:33:45 GMT</pubDate>
            <atom:updated>2024-02-05T20:33:45.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*g3NPW3sQSshHnFjG3uQaeA.png" /><figcaption>Risk management</figcaption></figure><h3>Introduction</h3><p>In the dynamic world of trading, the ability to eliminate emotional biases is crucial for success. This article explores the application of Python, a powerful programming language, to implement and execute risk management strategies based off live trade examples that I took last year when i was doing a $20,000 challenge account. By automating the decision-making process, traders can significantly reduce emotional interference and enhance the overall effectiveness of their trading endeavors. Join us on a journey into the realm of algorithmic trading, where Python becomes a valuable ally in the pursuit of disciplined and emotion-free financial decision-making.</p><h3>Historical trades</h3><p>My trading journal is all done on Excel as it gives me a lot of freedom to build statistics. These statistics includes pips on offer and pips in drawdown which allow me to run static tests on my trades to optimize my trading plan based off historical trades.</p><p>All of these calculations are not taking into consideration any fees. They are purely to see if there is a statistical edge in changing my risk management plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rB3HBh7p4cScNXOiYKoHA.png" /><figcaption>Historical trades</figcaption></figure><p>Upon reviewing my trading activity, it is evident that achieving the requisite 10% target for successful completion of Phase 1 took 42 trades. Within this dataset, it is notable that emotional factors led to several mistakes, thereby impeding the pace of my progress.</p><p>A comprehensive analysis of my trading journal reveals untapped potential in various trades, where a higher return could have been realized. However, a recurring issue was the tendency to prolong positions in an attempt to maximize gains from market movements.</p><p>To gain insights into the impact of alternative strategies on return, I conducted an evaluation of specific static scenarios. These scenarios include:</p><ol><li>Closing all trades at a 30-pip profit.</li><li>Assuming trades with less than a 20-pip profit were stopped at breakeven (BE) and subsequently closed at a 30-pip profit.</li><li>Closing all trades at a 10-pip profit.</li><li>Closing all trades at a 20-pip profit and implementing breakeven as soon as a position turned profitable.</li></ol><p>The findings indicate that a direct correlation between a higher win rate and increased return is not apparent. However, it is noteworthy that, in the context of my trading approach, there exists a trade-off between a lower win rate and the potential for mental fatigue. This suggests that a careful balance must be struck to optimize performance and manage psychological factors in pursuit of trading objectives.</p><h3>Risk Management Python</h3><p>Since scenario #4 had the highest yielding potential. The trades also had a hard stoploss value of 10pips so 20pips is just 2R. The other condition was that the trades moved into BE as soon as they were in profit. Since that cant be quantified what can be done is that say after 10pips or 1R the stoploss is moved to the entry price</p><p>Using the mt5 library to retrieve all the open positions and return them in a readable dataframe that can be used for further analysis:</p><pre><br>def OpenPositionsAsDF():<br>    list_current = mt5.positions_get()<br>    if len(list_current) ==0:<br>        return None<br>        <br>    else:<br>        # create a empty dataframe<br>        summary = pd.DataFrame()<br>        # create column names<br>        columns = [<br>                &quot;ticket&quot;,<br>                &quot;type&quot;,<br>                &quot;symbol&quot;,<br>                &quot;volume&quot;,<br>                &quot;profit&quot;,<br>                &quot;price&quot;,<br>                &quot;tp&quot;,<br>                &quot;sl&quot;,<br>                &quot;price_current&quot;,<br>                &quot;trade_size&quot;,<br>            ]<br>        # Loop to add each row in dataframe<br>        for element in list_current:<br>            trade_type = None<br>            if element.type == 0:<br>                trade_type = &#39;buy&#39;<br>            else:<br>                trade_type =&#39;sell&#39;<br>            <br>            element_pandas = pd.DataFrame(<br>                [<br>                    element.ticket,<br>                    trade_type,<br>                    element.symbol,<br>                    element.volume,<br>                    element.profit,<br>                    element.price_open,<br>                    element.tp,<br>                    element.sl,<br>                    element.price_current,<br>                    mt5.symbol_info(element.symbol).trade_contract_size<br>                ],<br>                index=columns,<br>            ).transpose()<br>            summary = pd.concat((summary, element_pandas), axis=0)<br>        return summary</pre><p>Calculating the risk to reward (RR) of open trades can be done easily using only the current, stop loss, and entry prices. Here is a function that does that for you automatically in python:</p><pre>def CalculateRR(sl:float, entry: float, current_price: float) -&gt; float:<br>    # difference between the stoploss and the entry price<br>    sl_entry_diff = abs(sl-entry)<br>    # difference between the current price and the entry price<br>    entry_curr_price = abs(entry - current_price)<br>    # divide the two and round them to 2 decimals<br>    rr = round(entry_curr_price  / sl_entry_diff, 2)    <br>    return rr</pre><p>As with all my scripts I like to add a precautionary function that ensures all my trades are within a certain percentage of capital available. This is labelled max capital allocation per trade. I don&#39;t want my position to be closed however I will make it so an alarm bell rings allowing me to be able to evaluate the situation when it arises:</p><pre><br>def CheckTradesRisk(balance: float, profit: float, max_bal_risked_percentage:float):<br>    # create a warning sound when risk is greater than max risk allocation<br>    risk =(profit / balance)<br>    if risk &gt;= max_bal_risked_percentage:<br>        for i in range(20):<br>            winsound.Beep(500, 1000)<br>            print(f&#39;WARNING!: {risk} is greater than {max_bal_risked_percentage}!!&#39;)<br>    else:<br>        return <br>    return</pre><p>Now all we need is a function to take partials and a function that moves our stops to entry:</p><pre>def Partials(position: pd.DataFrame, partial_size: float = 0.5) -&gt; str:<br><br>    # get the price at market<br>    tick = mt5.symbol_info_tick(position[&quot;symbol&quot;])<br>    # calculate the volume to close out<br>    partials = round(position[&quot;volume&quot;] * partial_size, 2)<br>    # Check that the partial volume is greater than the minimum volume<br>    info = mt5.symbol_info(position[&quot;symbol&quot;])<br>    if partials &gt;= info.volume_min:<br>        partials = partials<br>    else:<br>        raise ValueError(&quot;Partial volume is less than minimum volume&quot;)<br>    # make the request<br>    request = {<br>        &quot;action&quot;: mt5.TRADE_ACTION_DEAL,<br>        &quot;position&quot;: position[&quot;ticket&quot;],<br>        &quot;symbol&quot;: position[&quot;symbol&quot;],<br>        &quot;volume&quot;: partials,<br>        &quot;type&quot;: mt5.ORDER_TYPE_BUY if position[&quot;type&quot;] == &#39;sell&#39; else mt5.ORDER_TYPE_SELL,<br>        &quot;price&quot;: tick.ask if position[&quot;type&quot;]  == &#39;sell&#39; else tick.bid,<br>        &quot;deviation&quot;: 10,<br>        &quot;magic&quot;: 234000,<br>        &quot;comment&quot;: &quot;Partials&quot;,<br>        &quot;type_time&quot;: mt5.ORDER_TIME_GTC,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC,<br>    }<br><br>    # send the request to mt5<br>    result = mt5.order_send(request)<br><br>    # check if the order was made<br>    if result.retcode != mt5.TRADE_RETCODE_DONE:<br><br>        print(&quot;4. order failed, retcode={}&quot;.format(result.retcode))<br>        print(&quot;result&quot;,result)<br>        return result.comment<br><br>    else: <br>        return result.comment</pre><p>The default value for the partials is at 50% of the original value. This can be changed depending on the static results of the risk management strategies tested in Excel.</p><pre>def Breakeven(position: pd.DataFrame) -&gt; str:<br>    # make the request<br>    request = {<br>        &quot;action&quot;: mt5.TRADE_ACTION_SLTP,<br>        &quot;symbol&quot;: position[&#39;symbol&#39;],<br>        &quot;position&quot;: position[&quot;ticket&quot;],<br>        &quot;type&quot;: mt5.ORDER_TYPE_BUY if position[&quot;type&quot;] == &#39;sell&#39; else mt5.ORDER_TYPE_SELL,<br>        &quot;deviation&quot;: 10,<br>        &quot;sl&quot;: position[&quot;price&quot;],<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC,<br>        &quot;volume&quot;: position[&quot;volume&quot;],<br>        &quot;type_time&quot;: mt5.ORDER_TIME_GTC,<br>        &quot;comment&quot;: &quot;Breakeven&quot;,<br>    }<br>    # send the request to mt5<br>    result = mt5.order_send(request)<br><br>    # check if the order was made<br>    if result.retcode != mt5.TRADE_RETCODE_DONE:<br>        print(&quot;4. order failed, retcode={}&quot;.format(result.retcode))<br>        print(&quot;result&quot;,result)<br>        return result.comment<br>    else: <br>        return result.comment<br><br></pre><p>With all these functions they can be combined the desired risk management plan can be done without having to look at a price chart after the trade is entered.</p><h3>Conclusion</h3><p>In conclusion, the fusion of Python with MT5’s library emerges as a potent combination for implementing emotionless risk management strategies in trading. The utilization of algorithms provides traders with the adaptive capacity to respond dynamically to data insights. It is imperative to recognize that while historical performance serves as a guide, future outcomes remain uncertain. The proposed integrated approach not only empowers traders but also instills discipline and a data-centric mindset, allowing for a more informed and resilient trading experience in the ever-evolving financial markets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90fb565e2f31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding how the m5 timeframe moves inside a h1 timeframe]]></title>
            <link>https://medium.com/coinmonks/understanding-how-the-ltf-moves-inside-a-larger-timeframe-8e5db5f35a45?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e5db5f35a45</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 08:25:22 GMT</pubDate>
            <atom:updated>2024-01-24T09:48:59.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*T0xo12OGhOOp2WMW7YuReQ.png" /><figcaption>Low normalized (red) high normalized (green) close normalized (blue)</figcaption></figure><p>In this analytical study, we endeavor to examine the dynamics of 5-minute candle closes within hourly candles, employing sophisticated statistical techniques and comprehensive analysis. The initial phase involves categorizing the hourly candlesticks to facilitate their segregation for in-depth examination.</p><p>The primary objective of this report is to discern patterns and similarities in price movements. This exploration aims to provide traders with enhanced insights, enabling them to make informed decisions on when to remain in trades and when to exit. Time is identified as a pivotal factor in this analysis, emphasizing its critical role in influencing trading strategies.</p><p>Historical prices were taken from GBPUSD</p><h3>Candle Components</h3><p>A singular candle within a financial chart comprises three distinctive components, each contributing to the overall representation of market dynamics:</p><ol><li>Upper Wick: The upper wick reflects the price range between the highest traded value and the opening or closing level.</li><li>Body: The body of the candle is defined as the absolute difference between the opening and closing prices. It serves as a visual representation of volume (volume being prices traded over time) over the time frame its in.</li><li>Lower Wick: Representing the price range between the lowest traded value and the opening or closing price.</li></ol><p>Comparing these three components we can place candles into different categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*haaMDN2KqEaNSP0y4COcjA.png" /><figcaption>Candle components</figcaption></figure><h3>Categorizing candles on the h1 timeframe</h3><p>Many investors use candles to determine future prices of an asset. By categorizing them it gives traders a better understanding of market sentiment. In this section, we delve into the analysis of specific candlesticks such as Bullish/Bearish Engulfing, Hammer/Inverted Hammer, and Doji candles.</p><h4>Engulfing candles</h4><p>Bullish and bearish engulfing candle patterns are characterized by a specific criterion, denoted as:</p><p>a(Upper wick+Lower wick)&lt;Body</p><p>a = 2.5 which was calculated by comparing the results to the charts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*VN3Bu0etoc7KzCe_ibNm0w.png" /><figcaption>Bullish and Bearish engulfing candles</figcaption></figure><p>This condition is designed to identify candles where the body significantly outweighs the wicks. Considerations for refinement may involve adapting this criterion to ensure the candle size surpasses a predetermined threshold, thereby ensuring the candles are notably larger than the average.</p><p>It is imperative to underscore the significance of candle placement concerning neighboring candles. Upon comprehensive chart analysis, it has been observed that these candles are strategically positioned within ranges, either propelling price beyond the current range to initiate a new one or acting as overbought/oversold conditions that influence a directional shift in price movement. This nuanced understanding of candle placement is pivotal in interpreting market dynamics and potential price trends.</p><h4>Hammer</h4><p>Traders use hammer candles at the top of a move to denote a time in price where a leg up or down has exhausted itself and a retracement is coming. They can be defined by:</p><p>(body + Lower wick) &lt; Upper wick <br>(body + Upper wick) &lt; Lower wick</p><p>The color of the candle wasn&#39;t something that I included in the definitions as the report is on the movements inside the candles and not if they reverse from that point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*_6xLOp25rIdaZizAyiYXnA.png" /><figcaption>Hammer and Inverted Hammer candles</figcaption></figure><h4>Doji</h4><p>These candles are indecisive candles which traders use as signs of reversals or retracements if they are at a swing high or low.</p><p>They are defined by:</p><p>(Upper wick / Body) &gt; 1 and (Lower wick / Body) &gt; 1</p><p>Again, the color of the candles do not matter as what happens on the m5 does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*viLHs-QVfz9GCg9XLWjxRw.png" /><figcaption>Doji candles</figcaption></figure><p>Having successfully categorized the candles, the subsequent phase involves aligning the 5-minute (M5) charts with the hourly (H1) candle data. This alignment is accompanied by a normalization process, rendering the data comparable for discerning detailed patterns and similarities.</p><p>This meticulous approach seeks to unveil nuanced relationships between the finer details encapsulated within M5 charts and their corresponding H1 candle formations.</p><h3>M5 Timeframe</h3><p>The normalization process enhances the precision of the comparative analysis, providing a comprehensive foundation for identifying meaningful parallels in market dynamics. This analytical endeavor aims to distill valuable insights by aligning each m5 movements inside the h1 candles into a common y-axis for comparison.</p><p>This is the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*1TnfVrbi72wJjT8yvpeTNQ.png" /><figcaption>Normalizing formula</figcaption></figure><p>Once applying this formula to the close, high, low values plots can be made that will show how price moves inside the h1 candles.</p><p>There are many different hours of the day to chose from to compare but since the New York open is the most traded time I will extract only the 8am New York time plots</p><h3>Results</h3><p>The presented charts illustrate the categorization of H1 candles, each containing normalized M5 candles within its temporal span. The grey lines are all M5 normalized close values encapsulated within the respective H1 candle categories. Notably, the red, green, and blue lines within this framework denote the mean values corresponding to the low, high, and close of the M5 candles, contributing a comprehensive overview of the aggregated data within each H1 candle category.</p><h4>Engulfing candles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8rT3XZFA4v_UOsCOai0g-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lXyqBRXnwpgfK0AtRYZGuA.png" /><figcaption>Low normalized (red) high normalized (green) close normalized (blue)</figcaption></figure><p>The depicted graphical representations unveil a discernible surge in market liquidity at approximately 08:25, resulting in a notable expansion of the normalized value range between the market’s low and high points. It is imperative to underscore that, intriguingly, this surge in prices transpires just prior to the customary influx of news releases at around 08:30. This temporal misalignment suggests a nuanced dynamic, wherein market movements precede the anticipated impact of scheduled news events.</p><p>Of particular interest is the observed temporal lag in the bullish scenario, wherein the high values exhibit an initial upward trajectory, followed by a subsequent movement in the lows approximately 5 minutes later. Conversely, in the bearish context, a converse pattern manifests, emphasizing a distinctive temporal sequence in the evolution of high and low values. This temporal asymmetry prompts further investigation into the underlying factors influencing market dynamics during this critical timeframe.</p><h4>Doji</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3MdAf4gE0_5wzimFebrYxQ.png" /><figcaption>Low normalized (red) high normalized (green) close normalized (blue)</figcaption></figure><p>The observed doji candles exhibit a notable widening of the price range between their high and low values throughout the hourly candle. This characteristic divergence suggests a heightened state of market indecisiveness, wherein conflicting forces are exerting influence, resulting in a tug-of-war scenario that oscillates prices toward the mean candle price.</p><p>This intriguing phenomenon aligns with the identified surge in price change commencing around 08:25, a pattern consistently observed in engulfing candles during the same time interval.</p><h4>Hammer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*aoAXUx5_k0F17bIaXYUeVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sfZHR8B9I1SFy6ldKnKBTg.png" /><figcaption>Low normalized (red) high normalized (green) close normalized (blue)</figcaption></figure><p>Within the context of hammer candles, a discernible pattern emerges, particularly in conjunction with the surge of liquidity occurring around 08:30. Notably, this surge often intersects with key price levels, triggering a substantial and almost immediate reversal back towards the opening price.</p><p>This phenomenon implies a critical interplay of market forces during this temporal window. The surge in liquidity, likely influenced by external factors such as news releases, converges with specific price levels within the hammer candle formation.</p><h3>Conclusion</h3><p>The confluence of these findings implies a shared element in market behavior, wherein the forces contributing to price volatility and indecision manifest concurrently. Further exploration into the factors underlying this synchronized surge in price dynamics may yield valuable insights into the market’s response during this particular temporal window.</p><p>While creating the scripts for this I also took note on what times do these candles are likely to form through-out the trading session. It seems that the results for this are not as symmetrical as I thought they would be with some candles having a higher probability of forming at certain times that others.</p><p>If you are wanting the source code for this just DM me on <a href="https://www.linkedin.com/in/jaden-duxfield-2aa24225b/">Linkedin </a>and I can send it to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e5db5f35a45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/understanding-how-the-ltf-moves-inside-a-larger-timeframe-8e5db5f35a45">Understanding how the m5 timeframe moves inside a h1 timeframe</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using python to develop day trading strategies]]></title>
            <link>https://medium.com/@jadendux/using-python-to-develop-day-trading-strategies-53fe5910cbad?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/53fe5910cbad</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 07:44:05 GMT</pubDate>
            <atom:updated>2023-10-17T07:44:05.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*1mHun5bXTGzwAeavFqsfrw.png" /></figure><h4>Introduction:</h4><p>In the rapidly evolving landscape of contemporary finance, the development of effective trading strategies holds unparalleled significance. As financial markets increasingly embrace data-driven paradigms and cutting-edge technology, traders and investors are progressively turning to programming languages such as Python to gain a distinctive competitive advantage. This report delves into the captivating convergence of finance and technology, delving into the intricate realm of data analysis and its pivotal role in shaping trading strategies.</p><p>All the data employed in this study is openly sourced from forex.com, a reputable broker, and is readily available for download on their official website.</p><p>In order to effectively identify a market edge, the foundation of a well-defined trading approach is imperative. The various trading methodologies are distinguished by the timeframes for which positions are held. Concretely, swing trading engrosses trades unfolding over multiple days or weeks, day trading involves positions maintained within a single trading day, and scalping entails concise timeframes ranging from minutes to a few hours. This report places a distinct emphasis on scalping, given its propensity to yield rapid results, as well as some higher timeframe influence for more confirmation on the lower timeframe.</p><p>Through the utilization of Python, this report endeavors to shed light on the intricate process of dissecting data to derive valuable insights within the context of forex trading. By interweaving the realms of finance and technology, we embark on a journey to unravel the intricacies of market behavior&#39;s and harness the power of programming for enhanced trading strategies.</p><h3>Times used</h3><p>All the times referenced are from my broker which is GMT(+2).</p><h3>Seasonally</h3><p>We will start with market seasonality and work our way down to the lower timeframes where we endeavor to find specific and repeatable times that can be used in conjunction with market structure to predict future prices.</p><p>Python was used to find the averages of monthly prices using weekly data that was then used to find quarterly returns with a look back of 5 years. The look back of the last 5 years was used as there was a significant price change during covid that drastically changed the data so much so that a look back of 10–20 years will not yield much significance.</p><p>All charts show the average close price over a given year based off the last 2,5 and 15 years of data.</p><p>These seasonality charts can be used to determine biases coming into a new quarter or month. Looking at these monthly charts some similarities between the pairs can be used as confluence when going into chart on a daily basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qx9pccMjLruFS5Hh_gNNw.png" /><figcaption>GBP Seasonality and quarterly return</figcaption></figure><p>Examining the cable data reveals a clear pattern: as the lookback period increases, more noise is introduced, making it challenging to make accurate future predictions. When we analyze the returns for GBP, it becomes evident that there is a distinct upward trend during the earnings season. This is certainly something to take into consideration as we approach the fourth quarter.</p><h3>Weekly profiles:</h3><p>In preparation for the trading week ahead, traders routinely consult weekly and daily charts to shape their strategic perspectives. This pivotal phase involves a deliberation between two empirically supported scenarios, both substantiated by statistical evidence. Specifically, historical data indicates an 80% probability of price movements converging either towards the previous week’s high or low. Complementing this statistical foundation, traders incorporate technical analysis as an adjunctive tool to further refine their trading strategies.</p><p>Once traders establish their bias, they engage in speculative analysis of how the formation of five daily candlesticks may solidify their convictions. Python proves to be a valuable instrument in discerning the most prevalent weekly trading profiles based on historical data. It achieves this by initially assessing which trading days are more likely to contribute to the weekly highs and lows, building upon the trader’s pre-established weekly bias. This data-driven approach equips traders with a comprehensive framework for strategic decision-making in the dynamic world of financial markets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*D9ZHPYRvKiwM6kpIUyGxuQ.png" /><figcaption>Probabilities of a up close or a down close candle inside a bullish or bearish week</figcaption></figure><p>The analysis of these results unveils certain assumptions about the structural characteristics of bullish and bearish trading weeks, providing us with a statistical advantage. Python can be harnessed to segregate each weekly profile for more comprehensive examination.</p><p>For bullish conditions, the delineated profiles encompass the following scenarios:</p><ol><li>A week commencing with a low on Monday, culminating with a high on Friday.</li><li>A week characterized by a Monday low, followed by a high on Thursday.</li><li>A week initiated with a Tuesday low, reaching a high on Friday.</li><li>A week marked by a Tuesday low, subsequently concluding with a high on Thursday.</li><li>A week that commences with a Wednesday low and attains a high on Friday.</li><li>A week starting with a Wednesday low and concluding with a high on Thursday.</li></ol><p>In contrast, the bearish conditions, which represent the opposing market sentiment, mirror these profiles in an inverse manner, creating a comprehensive framework for analysing both bullish and bearish weekly trading scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RmJmHL2bZdkLB8UR6sEww.png" /><figcaption>Most common bullish week for GU</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amDpXeFfXXOTChlnzeks7g.png" /><figcaption>Most common bearish week</figcaption></figure><h3>Hourly</h3><p>The same analytical methodology applied to daily candle formations for speculative purposes over a weekly horizon can also be employed intraday to forecast the daily closing price. Once a directional bias is determined, hourly candlestick patterns can be used to anticipate the potential development of these trading sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*O_gz87us5U5bvJ1uo76g3A.png" /><figcaption>box plot of h1 candle returns</figcaption></figure><p>To do this the returns of the hourly candlesticks will be used as it normalizes the data around 0. With negative returns depicting lower prices and large returns showing volatility.</p><p>The vertical lines are there to show the start of the London session as well as the New York. The diamonds are outliers, and the bodies are where the majority of the returns are.</p><h3>Session Volatility</h3><p>Displayed below is a chart illustrating the hourly average pip sizes throughout the day, with the red line depicting the start of London session, and the blue is the start of the New York session. The average is measured in two distinct ways: one considering only the body size and another including both bodies and wicks. These measurements provide valuable insights into the timing of volatility surges within the market, helping you anticipate the day’s most significant price fluctuations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mprv-5eza-A3XC3dmyH08g.png" /><figcaption>Average pip size of each hourly candle</figcaption></figure><p>Knowing the average pip sizes of candles throughout the day, measured in both body size and body plus wicks, is highly beneficial for traders for several key reasons:</p><ol><li><strong>Volatility Assessment</strong>: It helps traders assess market volatility. By comparing the average pip sizes at different times of the day, they can pinpoint when the market tends to be more or less volatile. This information is crucial for adjusting trading strategies to match the current market conditions.</li><li><strong>Timing Trades</strong>: Traders can use this data to time their trades more effectively. When they anticipate higher volatility, they can enter the market during periods when the potential for larger price movements is greater, optimizing their entry and exit points.</li><li><strong>Risk Management</strong>: Understanding when to expect larger price moves allows traders to better manage their risk. During high volatility periods, they can adjust their position sizes and set appropriate stop-loss orders to protect their capital.</li><li><strong>Strategy Optimization</strong>: Traders can tailor their trading strategies based on this information. For instance, they might employ different techniques, such as scalping during low volatility times and swing trading during high volatility times.</li><li><strong>Market Insight</strong>: This knowledge provides traders with a deeper insight into market sentiment and dynamics. It allows them to gauge when significant news or events may be influencing price movements.</li></ol><p>In summary, understanding the average pip sizes of candles throughout the day empowers traders with valuable insights that can enhance their decision-making, reduce risk, and ultimately lead to more profitable trading outcomes.</p><h3>Session range</h3><p>In my analysis, I utilize the 15-minute chart to pinpoint specific time windows when the market experiences significant price swings, particularly focusing on the highs and lows during these overlapping sessions. This approach provides traders with added confidence, as they can align their day trading strategies with times when the market is most likely to make pivotal moves.</p><p>Moreover, I incorporate a well-established structural pattern known as the “Seek and Destroy” profile, as introduced by Inner Circle Trader (ICT). This pattern involves a deliberate sweep of the London session’s high (or low) before a subsequent movement in the opposite direction during the New York session. By identifying and understanding this pattern, traders can further enhance their trading strategies and capitalize on these predictable market behavior&#39;s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbO0nLK7HZAYKk7z4LT8Qg.png" /><figcaption>Times where daily highs and lows were formed</figcaption></figure><p>This chart effectively delineates the instances when the GBP/USD chart establishes its daily high and low points using 15minute candlesticks. Even without the need for vertical lines demarcating the trading sessions, the chart provides a clear visual representation of the distinct trading sessions. With New York providing the highest probabilities for picking the low or high of the day. There is also a spike at 15:30 is the time that high impact news events come out.</p><p>I have generated a graphical representation comparing the AUDUSD currency pair to underscore the variations in data dynamics among different pairs. This analysis highlights that the operational hours of the Reserve Bank of Australia, primarily during the Asian trading session, considerably contribute to the probability of establishing daily high and low price points. This phenomenon is particularly evident during the Asian session due to its prominent influence on price action. Conversely, the London trading session often exhibits relatively subdued price movements, as it awaits the commencement of the New York session for notable market activity to unfold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEp8Wl7SI5vPbdR9oW9FFA.png" /><figcaption>AUDUSD</figcaption></figure><h3>Asia session:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Me_s8UeHxBFlCV285JoKzA.png" /><figcaption>Times where high/low of the session formed during Asian session</figcaption></figure><p>Looking at the chart it is clear there are specific times during the session where the high and low of the session have a higher probability of forming and can be used to capture the entire range.</p><h3>London session:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCxutoUAX7P-lKGJRw0P9g.png" /><figcaption>Times where high/low of the session formed during London session</figcaption></figure><p>The London open provides a good opportunity to be able to capture the London range with the last 15mins being where majority of the session creates the low or high of the session.</p><h3>New York session:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KC4Hn8jmvmeSaBnclhIIjw.png" /><figcaption>Times where high/low of the session formed during NY session</figcaption></figure><p>The overlap between the London and New York session is evident by the frequent occurrence of high or low price points</p><h3>Hourly profiles</h3><p>The analysis of M15 candlestick formations within hourly (H1) candlesticks is a focal point for traders who hold positions for an hour or longer. This analysis delves into how the average prices evolve within the context of H1 candlesticks, often substantiated by confirmatory signals from lower timeframes. This comprehension equips traders with the confidence to enter trades at precisely opportune moments within the hourly timeframe. By scrutinizing the interaction between M15 candles and H1 candlesticks, traders gain pivotal insights into the likely emergence of high and low points, thereby enriching their decision-making processes and bolstering their trading strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ym-NCEOZsBMK-wvV9CUU2w.png" /><figcaption>Return of 15min candlesticks inside 1hr windows</figcaption></figure><p>The two methods I used are:</p><ol><li><strong>Return (Average Price of Bodies):</strong> This method calculates the average price by considering the bodies of the candlesticks. The candlestick body represents the price range between the opening and closing prices during the given time period (e.g., M15 or H1). Discrepancies in this method can occur when the candlestick bodies vary significantly within the selected time frame, reflecting changes in market sentiment and price momentum.</li><li><strong>High-Low (Average Price of Wicks):</strong> This method computes the average price by taking into account the high and low prices (wicks) reached during the same time frame. Variations may arise if the wicks exhibit notable fluctuations, which can be influenced by factors such as market volatility, liquidity, or the occurrence of significant news announcements.</li></ol><p>It’s crucial to emphasize that both of these methods exclusively represent the price dynamics within the M15 timeframe of the hourly candlestick. Within this context, certain patterns emerge:</p><ul><li>The initial 15 minutes frequently witness significant price fluctuations, characterized by notable movements.</li><li>Between the 15 to 30-minute window, the price tends to exhibit a propensity for stability, often leading to minimal changes.</li><li>During the final 15 minutes, substantial price shifts are more likely to occur, particularly when the hourly candlestick is closing in a bearish manner.</li></ul><h3>Conclusion</h3><p>Utilizing this data-driven methodology in the realm of forex trading proves highly advantageous when seeking to construct a systematic trading strategy. Through this approach, traders can pinpoint precise moments within the day when they anticipate specific market behaviors. Moreover, they can operate with confidence, drawing strength from the statistical advantage afforded by a system crafted through Python-based analysis and development.</p><h3>Links:</h3><p>Github repo:<br><a href="https://github.com/MrPotatoHead-Dev/Forex-trading-strategy-development">https://github.com/MrPotatoHead-Dev/Forex-trading-strategy-development</a></p><p>Linkedin:<br><a href="https://www.linkedin.com/in/jaden-duxfield-2aa24225b/">https://www.linkedin.com/in/jaden-duxfield-2aa24225b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53fe5910cbad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SMT Divergence review on a 5minute timeframe]]></title>
            <link>https://medium.com/@jadendux/smt-divergence-review-on-a-5minute-timeframe-45f3935fd202?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f3935fd202</guid>
            <category><![CDATA[ict]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[currency]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 03:31:25 GMT</pubDate>
            <atom:updated>2023-03-10T03:31:25.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*yC8bD_uzAvaL7VvHu0RnrA.png" /><figcaption>ICT’s logo</figcaption></figure><h3>Introduction</h3><p>The forex market is an ever-changing landscape, with prices constantly fluctuating as traders buy and sell currency pairs in response to economic and political events. To navigate this complex environment, traders often rely on trend analysis, using technical indicators to identify patterns and predict future price movements. One such pattern which is taught by ICT, is SMT divergence, which occurs when the short-term trend of a currency pair differs from a correlating pair, signifying smart money accumulation before the higher timeframe trend continues. This phenomenon can be a powerful signal for traders, indicating a potential reversal of the longer, and short-term trend. By understanding the significance of SMT divergence, traders can make more informed decisions and achieve greater success in their trading strategies.</p><h3>Assumptions</h3><p>In backtesting, assuming that the draw on liquidity from higher timeframes is already known enables the identification of the underlying price dynamics that are not directly impacted by the higher timeframes. This allows for a more granular analysis of the price movements and liquidity dynamics on the lower timeframes.</p><p>Overall, by considering the influence of higher timeframes on liquidity, backtesting on lower timeframes can provide a more detailed understanding of the market’s microstructure, which can inform trading decisions and risk management strategies.</p><h3>Methodology</h3><h4>Linearizing data</h4><p>Correlation coefficient matrices is a very common tool used in statistical analysis to determine if the two datasets have a relationship. When applying the matrices to OHCL data it is important to linearize the data. This can be done in 3 ways:</p><ol><li>(Open + High + Low) / 3</li><li>(Open + high) / 2</li><li>Close</li></ol><p>These are the functions that were used in python to efficiently add these columns to the pandas dataframe:</p><pre>def hlc3(row):<br>    return (row[&quot;high&quot;] + row[&quot;low&quot;] + row[&quot;close&quot;]) / 3</pre><pre>def hl2(row):<br>    return (row[&quot;high&quot;] + row[&quot;low&quot;] ) / 2</pre><h4>Correlation coefficient</h4><p>In statistical analysis the Pearson&#39;s correlation coefficient is a powerful tool used to measure the relationship between two datasets. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*0kNaZ-IDZvmm-T86.JPG" /><figcaption><a href="https://www.analyticsvidhya.com/blog/2021/01/beginners-guide-to-pearsons-correlation-coefficient/">https://www.analyticsvidhya.com/blog/2021/01/beginners-guide-to-pearsons-correlation-coefficient/</a></figcaption></figure><p>The output of the Pearson correlation coefficient is a single value between -1 and 1, where:</p><ul><li>A value of -1 indicates a perfect negative correlation, meaning that as one variable increases, the other variable decreases in a perfectly linear fashion.</li><li>A value of 0 indicates no linear correlation, meaning that there is no linear relationship between the two variables.</li><li>A value of 1 indicates a perfect positive correlation, meaning that as one variable increases, the other variable increases in a perfectly linear fashion.</li></ul><p>The closer the Pearson correlation coefficient is to -1 or 1, the stronger the linear relationship between the two datasets. If the coefficient is close to 0, there is no linear relationship between the two variables. The sign of the coefficient (+ or -) indicates the direction of the relationship: a positive coefficient indicates a positive relationship (as one variable increases, the other variable tends to increase), while a negative coefficient indicates a negative relationship (as one variable increases, the other variable tends to decrease).</p><h4>Pivot points</h4><p>This function was made by CodeTrading on YouTube for his video on RSI divergence: <a href="https://www.youtube.com/watch?v=3d5RTto5fKY">https://www.youtube.com/watch?v=3d5RTto5fKY</a></p><pre>def pivotid(df1, l, n1, n2):  # n1 n2 before and after candle l<br>    if l - n1 &lt; 0 or l + n2 &gt;= len(df1):<br>        return 0<br>    pividlow = 1<br>    pividhigh = 1<br>    for i in range(l - n1, l + n2 + 1):<br>        if df1.low[l] &gt; df1.low[i]:<br>            pividlow = 0<br>        if df1.high[l] &lt; df1.high[i]:<br>            pividhigh = 0<br>    if pividlow and pividhigh:<br>        return 3<br>    elif pividlow:<br>        return 1<br>    elif pividhigh:<br>        return 2<br>    else:<br>        return 0</pre><p>ICT defines swing highs and lows on the identification of a single candle with both a lower low or higher high on each of its sides. However, this method has been found to produce an excessive amount of noise for this analysis. As such, an alternative approach has been adopted, wherein swing highs are defined as having a minimum of five lower candles on either side, while swing lows are identified by a minimum of five higher candles on either side. This revised methodology has been found to be more effective in reducing the amount of extraneous data and enhancing the overall accuracy of the analysis. Its important to note that this way of defining swing points live could be too slow.</p><h4>Slope</h4><p>Finding the slope between the pivot points is used to determined the overall trend of the market at that point in time. If the market is making higher highs then these pivot points will return a positive value when returning pivot[-1] — pivot[-2]</p><pre>def slopeSignal(df):  # finding trend using pivots (HH, HL...)<br>    slopeLow = []<br>    slopeHigh = []<br>    lowPoints = []<br>    highPoints = []<br>    trendHighs = [np.nan] * len(df)  # initialize with np.nan values<br>    trendLows = [np.nan] * len(df)  # initialize with np.nan values<br>    for i in range(1, len(df) - 1):<br>        if df[&quot;pivot&quot;][i] == 2:<br>            highPoints.append(df[&quot;high&quot;][i])<br>            if len(highPoints) &gt; 1:<br>                slopeHigh.append(highPoints[-1] - highPoints[-2])<br>                if len(slopeHigh) &gt; 1:<br>                    if slopeHigh[-1] &gt; 0:<br>                        trendHighs[i] = True<br>                    if slopeHigh[-1] &lt; 0:<br>                        trendHighs[i] = False<br>        if df[&quot;pivot&quot;][i] == 1:<br>            lowPoints.append(df[&quot;low&quot;][i])<br>            if len(lowPoints) &gt; 1:<br>                slopeLow.append(lowPoints[-1] - lowPoints[-2])<br>                if len(slopeLow) &gt; 1:<br>                    if slopeLow[-1] &gt; 0:<br>                        trendLows[i] = True<br>                    if slopeLow[-1] &lt; 0:<br>                        trendLows[i] = False<br>     for i in range(1, len(df)):<br>        if np.isnan(trendHighs[i]):<br>            trendHighs[i] = trendHighs[i - 1]<br>        if np.isnan(trendLows[i]):<br>            trendLows[i] = trendLows[i - 1]<br>      df[&quot;trend highs&quot;] = trendHighs<br>      df[&quot;trend lows&quot;] = trendLows<br>      return df[&quot;trend highs&quot;], df[&quot;trend lows&quot;]</pre><p>At first it is important to initialize the nan values as to ensure that the data frames have the correct length when trying to add this to the main data frame.</p><h4><strong>Divergence</strong></h4><pre>def divergence(df1, df2):  # returns dates, times<br>    merged_dates = df1.merge(df2, on=[&quot;date&quot;, &quot;time&quot;], suffixes=(&quot;_1&quot;, &quot;_2&quot;))<br>    divergence_dates = set(<br>        merged_dates.loc[<br>            (merged_dates[&quot;trend highs_1&quot;] != merged_dates[&quot;trend highs_2&quot;])<br>            | (merged_dates[&quot;trend lows_1&quot;] != merged_dates[&quot;trend lows_2&quot;]),<br>            &quot;date&quot;,<br>        ]<br>    )<br>    merged_times = df1.merge(df2, on=&quot;time&quot;, suffixes=(&quot;_1&quot;, &quot;_2&quot;))<br>    divergence_times = merged_times.loc[<br>        (merged_times[&quot;trend highs_1&quot;] != merged_times[&quot;trend highs_2&quot;])<br>        | (merged_times[&quot;trend lows_1&quot;] != merged_times[&quot;trend lows_2&quot;]),<br>        &quot;time&quot;,<br>    ]<br><br>    return (divergence_dates), (divergence_times)</pre><p>The merge() function in Pandas is a powerful tool for combining two datasets with a shared index, such as date and time, and can also be customized to include suffixes for columns with identical names.</p><p>In the context of identifying divergences between datasets, the merge() function can be used to compare trends and identify dates where they differ. This date information can then be extracted and used for further analysis, such as plotting only the days where the divergences occur. To prevent duplication of dates with multiple divergences, a set data structure can be utilized to ensure that only unique dates are retained.</p><p>Overall, the merge() function offers an efficient and effective way to merge and analyze datasets with shared indexes, providing valuable insights for data-driven decision making.</p><h3>Findings</h3><p>After analyzing around one year’s worth of data, I evaluated the correlation between the three linear data. Upon comparison, the linear formula of (high + low) / 2 displayed the highest correlation coefficient, indicating a stronger linear relationship between the two variables. As a result, this linear formula was utilized for the remainder of the analysis, and its utilization allowed for a more accurate representation of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*n1NbWlA2o8BqKr4jW0mDKw.png" /><figcaption>Correlation coefficients of the pairs</figcaption></figure><h4>SMT Divergence</h4><p>Here is an example of SMT Divergence during the London session. It can be observed that EU price makes a final sweep of liquidity before continuing in GU’s direction. In this image there are multiple opportunities to exploit the differentiation in price that occurs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgxz66e3yi8UsvswVfpqWw.png" /></figure><p>After calculating all correlation coefficients, a detailed examination of plots spanning one year was performed manually to identify pairs with high correlations that may deviate from each other, thus creating trade opportunities. This examination also involved matching correlation coefficients against days of the week to ensure data accuracy. Although no clear leader emerged, both pairs displayed similar results, indicating that the London session has the clearest times for such occurrences. The analysis excluded major news-driven days and minor divergences, as the aim was to determine the leading or lagging behavior of the pairs, and not to alter the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*T3zvsLYI0uf1S47OxTJ8Bg.png" /><figcaption>Manual review of the SMT divergence between EU and GU</figcaption></figure><h4>Normalized combined charts</h4><p>The observation of plotting the three normalized pairs together reveals an intriguing phenomenon in forex trading. One pair enters an accumulation phase, while the other two begin trending, resulting in a dynamic where the accumulating pair experiences an aggressive move to catch up with the trending pairs. This behavior can offer valuable insights for traders seeking to capitalize on market trends and fluctuations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbe77QJtXMBiAsLuRO_vKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gza9A5MLW_InjEeqSztjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwxkjdpxupHYjnP4BWlvYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LL2T0f7EPAJzdqsOl2XpIQ.png" /><figcaption>Plotting the three pairs together with vertical lines denoting London and NY open</figcaption></figure><h3>Conclusion</h3><p>This study provides compelling evidence of the synchronized behavior of forex pairs. However, it’s worth noting that when examining individual trading days, the correlation coefficient can dip as low as 0.40. <br>While incorporating these three charts into a trading plan may prove effective, traders must consider other market factors that can impact intraday trading outcomes.</p><p>Manual sifting through the data revealed that when divergences between the EU and GU pairs occurred, it was often due to one pair seeking liquidity before the onset of a trend. This underscores the importance of closely monitoring liquidity levels and identifying trends early on to maximize trading opportunities.</p><p>I tried using the correlation as a type of indicator to determine how price reacts when it gets to a local minima or maxima value however this process was not successful.</p><p>Here’s a link to the code base:<br><a href="https://github.com/MrPotatoHead-Dev/SMT-Divergence-review">https://github.com/MrPotatoHead-Dev/SMT-Divergence-review</a></p><p>Link to ICT’s teaching on it:<br><a href="https://www.youtube.com/watch?v=isXicdayBwA">https://www.youtube.com/watch?v=isXicdayBwA</a></p><p>Thank you for your time,</p><p>Have a good day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f3935fd202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three Gas Optimization Strategies For Ethereum Smart Contracts]]></title>
            <link>https://coinsbench.com/three-gas-optimization-strategies-for-ethereum-smart-contracts-c44e9f7ab47d?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/c44e9f7ab47d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[remix]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 01:14:00 GMT</pubDate>
            <atom:updated>2023-01-24T16:00:23.385Z</atom:updated>
            <content:encoded><![CDATA[<p>Saving gas in Solidity is an integral part of developing smart contracts on the Ethereum blockchain. Gas is the internal pricing for executing a transaction or contract on the Ethereum network, and reducing it is key for ensuring financial viability for users and preventing network congestion. To reduce costs, developers should test their code thoroughly and ensure that all optimizations are found before deploying to the mainnet. A few methods to reduce gas costs include using inline assembly, optimizer settings, and writing code with less complexity. It is important to note that the Solidity compiler is still in development and improvements are being made to reduce gas costs as well. Smart contract developers should take advantage of these improvements when available to ensure their contracts remain optimized and cost-effective. Ultimately, when developing smart contracts on the Ethereum network, saving gas should be a priority in order to achieve maximum efficiency and cost-effectiveness.</p><p>These gas prices are just estimations generated from the testnet I was using and should be used only as guides for how it would be in a live environment.</p><h3>Test one: Arithmetic</h3><p>Reading the documentation for solidity is vital to stay up to date with the latest versions of the compiler. Upon my reading, I noticed that versions less than 0.8.0 were using additional checks on arithmetic operations to ensure there was not any over/underflow of variables. These additional checks cost the developer more gas. With the new versions of the compiler, it can be as simple as wrapping an ‘unchecked’ box around the arithmetic. This can save roughly 10%</p><p>Here is a quick example of how it can be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*WbW3LlFSa_30EPKIXxwp8A.png" /><figcaption>Test one</figcaption></figure><p>Gas cost: 98553.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*uQPq_DiYCpFKYXdbUDnvNg.png" /><figcaption>Test one — unchecked</figcaption></figure><p>Gas cost: 87557.</p><h3>Test two: Errors</h3><p>Newer versions of solidity have removed custom errors and replaced them with if statements. I have compared them with the simple require() statements. Both of them were also tested with and without string messages. It can seem obvious that with a string it will occur more gas however I will test it anyway so we can have a monetary value on the difference between with and without a string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*pW8BZBYanPuAHdrUKFIiLQ.png" /><figcaption>Test two — if statements</figcaption></figure><p>Gas cost: 99657 (with string)<br>Gas cost: 87809 (without string)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*srORuIi_TujTqMw48OkOGw.png" /><figcaption>Test two — require</figcaption></figure><p>Gas cost: 99441 (with string)<br>Gas cost: 86885 (without string)</p><p>An additional 10% in cost savings can be achieved by utilizing the ‘require’ statement to impose specific conditions within a smart contract function. In a subsequent test, I implemented the use of ‘modifiers’ such as the typical ‘onlyOwner()’ as conditions prior to executing a function. However, no cost savings were observed in this scenario. This may be due to the fact that the modifier was only utilized in a single function and was not invoked during execution. It is worth noting that cost savings may be more pronounced when a modifier is used to reject a function call, as the modifier would then be executed in lieu of the entire function.</p><h3>Test three: Mappings</h3><p>Mappings are key-value pairings that can store any type of value as the key and value. These keys are stored in a hash table, which means that mappings do not have a specific size or limit the number of elements that can be stored. Arrays on the other hand can have a fixed size, or they can be dynamic arrays. The elements of the array are stored in a specific order, allowing for more efficient storage of data, and easier access by developers. Thus, while both mappings and arrays allow the storage of data in smart contracts, they each have their own unique characteristics which should be taken into account when making decisions about how to store data. I tested both mappings and arrays to see the difference in gas costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*kRxnPfzQeR6-EuP5hRPNsA.png" /><figcaption>test three — mappings</figcaption></figure><p>Gas cost: 101769</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*AqwLurekMY_w9gIT6hZ-hA.png" /><figcaption>three — array</figcaption></figure><p>Gas cost: 123879</p><p>Around 20% savings can be made when using mappings. However, developers may struggle to always use mappings instead of arrays as arrays are a lot easier to access.</p><h3>Conclusion</h3><p>The results of my tests underscore the importance for developers of leveraging the latest version of the Solidity compiler and new features, such as using ‘unchecked’ blocks, to save around 10% in gas costs. Additionally, developers should also take into account their data storage choices to optimize their smart contracts. Mappings can save up to 20% in gas costs compared to arrays but are less accessible; whereas arrays are easier to access but come at a cost. Developers must consider these factors when creating smart contracts to ensure that they are getting the most out of their smart contracts while minimizing cost and maximizing efficiency. By taking advantage of the latest Solidity compiler and being mindful of data storage solutions, smart contract developers can optimize their code and ultimately create more successful projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44e9f7ab47d" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/three-gas-optimization-strategies-for-ethereum-smart-contracts-c44e9f7ab47d">Three Gas Optimization Strategies For Ethereum Smart Contracts</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using OHCL data to determine the significance of the ADR indicator plus a bonus analysis (GBPUSD)]]></title>
            <link>https://medium.com/@jadendux/using-ohcl-data-to-determine-the-significance-of-the-adr-indicator-plus-a-bonus-analysis-gbpusd-6356e0caaea5?source=rss-1b2d0aca2876------2</link>
            <guid isPermaLink="false">https://medium.com/p/6356e0caaea5</guid>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[forex]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Jaden Duxfield]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 03:05:43 GMT</pubDate>
            <atom:updated>2023-03-04T20:38:55.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As an analyst in the forex market, it can be a very daunting task to look at, draw some lines, and conclude that we are going in X direction while the market goes to Y, and we are left with less money than before, and hopefully not liquidated.</p><p>After I read the book by Larry Williams, “Long-Term Secrets to Short-Term Trading”, I am intrigued by his approach to the markets and how he came up with these extremely basic trading strategies based on the data that he was able to collect in a time where they printed off charts and manually drew on them as part of their daily analysis. That is true dedication to trading and if someone is wanting to participate in the markets full time then that approach is needed. However as I comb through twitter and these discord communities I find that the majority of people are asking for other people&#39;s work and asking questions that can only truly be answered by putting in the work yourself and reading the tape.</p><p>From the inspiration of Larry Williams and ICT, I decided to do my own research and analysis of the markets in my own way.</p><p>The Average Daily Range is a common indicator for traders to use with changeable values that traders don’t bother to acknowledge or customize the values based on what they were told to use. This can lead to false data and a misinterpretation of the significance of the set values and how a simple analysis can be done on EXCEL to determine the accuracy on certain pairs, as my understanding of forex tells me that not all pairs work the same and would, of course, need certain customizable tools unique to the pair. I also view the market as a machine that is constantly changing and adapting based on the information it is receiving.</p><h3>Method</h3><p>The data that was collected was from MT4’s Historical Data selection. I am uncertain of the accuracy of this data but from sifting through it I saw that 1Hr was left over on Saturday that was deleted and there are about 2 weeks of Wednesday data that aren’t included but since I was taking the data from 2004 onwards missing 2 Wednesdays and the Saturday data shouldn’t affect the analysis too much. Unless of course Fridays kept showing up with low and obscure values relative to the other days of the week.</p><h3>Pair</h3><p>GBPUSD</p><h3>Formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*ruiTYfJIOgH8KR89vS_anQ.png" /><figcaption>The formula for calculating the ADR</figcaption></figure><p>Let&#39;s move to the fun part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jW9BGDWiSNFjRnb0eYEZ_w.png" /><figcaption>The excel spreadsheet</figcaption></figure><p>The tedious part of the entire project was manually sifting through the data to find the days that were missing so that I could cut those weeks out, and reset the formulas. I&#39;d like to note that ideally, it wouldn&#39;t really matter where the formula started from as long as it was over a consecutive amount of days and therefore showed if the market is in a consolidation before an expansion.</p><p>For ease of interpretation, I will use the phrase ‘true range’ to denote the actual range of the day and the ADR value as the one used from the formula. <br>Looking at the data the most important part is the percentage, as this is the percent difference between the true range and the ADR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*yzFmaXK27zupb4GrJwBtuQ.png" /><figcaption>ADR with 3, 5, and 10-day look back</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*tbDU4FL61d9bEU9Z0zx8sQ.png" /><figcaption>ADR with 15 and 20-day look back</figcaption></figure><p>The middle column here isn&#39;t important. it&#39;s only there for me to get the percentage.</p><p>These tables show the ADR over 3 to 20 days, I then counted the number of days the data was between 0–80%, 0–90%, 0–100%…. from 150% I changed the formula to count the days between 100% and 150%. The same was done for 200% and 250%. 250% was the highest value I took as the minima isn’t important. My focus is on the maximum which lay around 110%.</p><p>Looking at these tables ADR3 had the best accuracy with a high probability of the data being within 110% of the daily range. This is perfect. If a casino has a 57%-win rate to make millions or even billions of dollars a year we now can look at the charts and say “ok price has a 54% chance of being between X &amp; Y values. As price starts to print towards the 100% mark and we are given a reversal structure we now have added confluence that there will be a reversal or a pullback.</p><p>While I had this data in excel I decided to do some more analysis to determine other characteristics of this pair.</p><h3>Daily Average Range</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*SNdqlTor7wEoAZ8ghKXriw.png" /><figcaption>Average Range</figcaption></figure><p>Monday is the beginning of the week and most traders know that this day is a consolidation most of the time, while Wednesday is the day most high-impact news drivers come.</p><h3>Bullish/bearish days</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*IuL23-SvN4IIuTPvBIb5AQ.png" /><figcaption>bullish/bearish</figcaption></figure><p>Firstly, take into consideration rounding. Even if they are inaccurate by a factor of .1% it still doesn&#39;t matter. When I look at this all I see is Wednesday. This 53% value is a considerable difference between the others. I use this all the time in my trading. Now what I did next was separate weeks that close bearish from the weeks that close bullish and did the same analysis.</p><h3>Bullish Week</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*H_QMRrcT3OSuZKQ_s1QP7A.png" /><figcaption>Bullish weekly close</figcaption></figure><p>This ties in nicely with ICT’s weekly profiles. Monday seems to be a false move with the high time frame (HTF) target being hit by Wednesday.</p><h3>Bearish Week</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*1eolasWvrAmSpfkUWXaEoA.png" /><figcaption>Bearish weekly close</figcaption></figure><p>Mondays seem to be the day of the false move but what is interesting is how bearish weeks have a significantly higher chance of Fridays being bearish.</p><p>Comparing both sets of data it is clear Wednesdays seem to have a high probability of being closed bullish.</p><h3>Conclusion</h3><p>Looking at all this data it is clear that when using the ADR indicator it is more accurate to use the 3-day look back and ensure that the indicator allows for different percentage levels to be added, more specifically the 110%. Don&#39;t take the values as truth because 50% odds is still a toss of a coin so all this should do is add as an extra layer of confluence that could equate to a profitable trade. A lot of this analysis of the daily profiles does prove ICT’s theory which is good to see. Thank you</p><p>Thank you for reading. During my journey as a trader, I have written many reports like this that I have kept to myself as indicators of my progression.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6356e0caaea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>