Automated Price Break Out Detection: Algorithmic Trading In Python
ฝัง
- เผยแพร่เมื่อ 10 ก.พ. 2025
- Unlock the power of automated price breakout detection with our Python coding tutorial! In this video, we delve into creating a breakout indicator that can identify key levels based on multiple bounces in a trading asset's price. The script covers the coding process step by step, and you can find the downloadable source code in the description below.
📈 Pattern Detection and Key Zones:
Learn how to recognize patterns where an asset bounces multiple times around an average key level. We define key zones rather than exact levels, allowing for flexibility in tuning. The algorithm observes price movements, generating breakout signals when a candle closes above the upper zone edge for a bullish breakout or below the lower zone edge for a bearish setup.
⚙️ Customization and Combination:
Discover the versatility of this breakout strategy by combining it with other indicators like the moving average. We explore how to use the breakout pattern in conjunction with the MA curve to identify potential uptrends or downtrends, providing valuable insights into market momentum.
🧠 Algorithm Parameters and Avoiding Bias:
As we dive into coding, we consider essential parameters like the gap window and backcandles window to prevent lookahead bias. The gap window ensures accurate signal detection, while the backcandles window defines the range for identifying pivot points and support/resistance levels.
🔧 Code Along - Python Automation:
Follow along as we code the entire process in Python, automating the detection and signaling for breakout patterns. Our approach ensures practicality and adaptability, allowing you to explore different scenarios by adjusting the width of the key zone.
📊 Enhance Your Trading Strategy:
Whether you're a beginner or an experienced trader, incorporating automated breakout detection can significantly enhance your trading strategy. Stay ahead of market trends and capitalize on potential opportunities with this comprehensive Python tutorial.
💲 Discount Coupon for My Udemy course on Algorithmic Trading:
bit.ly/CouponA...
Download the Source Code:
drive.google.c...
And the Data file:
drive.google.c...
👍 Like, Subscribe, and Share for More Insights:
If you find value in this tutorial, don't forget to like, subscribe, and share with fellow traders and coding enthusiasts. Stay tuned for more coding experiments, algorithmic trading insights, and practical tutorials to elevate your financial journey. Happy coding! 🖥️📈 #tradingalgorithms #pythoncoding #breakouttrading
I'm a beginner. I learnt a lot from this video. Thanks.
Glad it was helpful! Thank you for your comment.
You have no idea how I tried to code this trendline with Python today and my head almost caught fire and it wasnt working well😂. I just finished coding now I was comparing with yours and i must say your code is pretty beautiful 🎉.
Thank you very much. Am looking forward to re coding it in a new way.😮
Glad it helped! my code is not as elegant there are some improvements to make it more professional... but it works :)
@@CodeTradingCafe paste your code to chatgpt & ask it to optimize :)
You are so kind, may Almighty bless you with loads of happiness and success brother, you are helping people who need it
Good luck to you !
Thank you. This one is one of the most honest and capable work.
I appreciate that! Thank you!
Excellent work! Thanks. A future modification can be to add code that validates a breakout. You want to avoid fake breakouts. This can only be validated when a breakout is detected followed by a retest of the identified level then a confirmation candle in the right direction is detected. I would also add volume to the algorithm. A good breakout always occurs with strong volume
Thank you for the tip I will keep it for a future video.
A code masterpiece !!! Chapeau !!!
Thank you for your constant support!
Damn Python seems soooo nice !! I begin an introductory course and will clearly go through your content as soon as I'll be more geared !
Sooo tired of backtesting manually... Would rather like to code for 10h instead instead of having to do 1000h of backtesting...
Manual backtesting is tiring, you will enjoy python and the possibilities are endless.
I subscribe and registered your udemy course. Very neat and clear explanation, i hope i'll that good soon. Thank you. 😊
Best of luck, and mostly enjoy learning, thanks a lot for your support.
first of all thank you u so much for such great effort
i have 2 questions
1 - how we can start use this in a real time data instead of historical so we can detect what breakouts of current market
2 - and how we can get a notification for any break out signal for example on our email
what am trynna say i want to Strat using this indicator for real time trading
Hi, thank you for your comment, for real time data you need to connect through your brokers API, as an example check this video: th-cam.com/video/WcfKaZL4vpA/w-d-xo.html
Regarding the notifications check this one:
th-cam.com/video/YYJ6iRXSy6Y/w-d-xo.html
Good luck!
Great tutorial and clear explanation!
Glad it was helpful! thank you!
Hey very nice code video. one suggestion that for learning purpose you can take candle index and plot it on different chart. for example chart1 = 0 to 2000 and chart2 = 2001 to 4000 etc. and so on.
Thank you for your support, and for the tip, actually yes we can split into different figures.
I really enjoy your content. An idea for a video that would be interesting to me and probably others: managing different time periods / higher time frame confirmations. When I use pandas to resample, it will do stuff like adding in weekends automatically with NaN values which is annoying (I probably don't understand the most efficient ways to do this). Also, would be interested to seeing your approach to building a signal function or stop loss strategy that look at multiple time frames simultaneously -- for instance, look for price break out at 5M but only go long if 4H is in uptrend. Keep up the good work! 👍
Thank you so much for your support. Multi-timeframe trading is definitely a good idea that was requested before, my bad I am trying to avoid synching frames together just afraid of the quality of the data. But... I must do it!
@@CodeTradingCafe my idea for how to do this (which I'm planning to work on soon) is to use dt.hour and dt.minute dataframe operations to find if my current 1M candle is within the range of larger 15M candle (for instance). no idea if this is the best approach but seems reasonable to me. If I put together something working before you post a video about this, I'll send the code your way.
I think once the multi timeframe approach is opened, there is plenty to investigate, the more I am thinking about it the more I feel it's a priority now.
you can use this line of code to get rid of the NaN's in pandas dataframe:
item.table.dropna(inplace=True)
Actualy we dont need higher timeframe because in every timeframe it self have full info about MS. Break on 4h equal 5m. Many trader need high timeframe because they analyze with two eyes. We just get a lot ohlcv item.
Thank you for this very beautiful video. And code ❤
Glad you liked it! thank you for your support!
Have you created any video on converting live market stream data to OHLC candles and then analyzing any of your strategy live and if it matches perform buy or sell order based on signals?
Hi, check this video, it's a live trading bot testing: th-cam.com/video/bZhtvvFm17A/w-d-xo.html
Do you have a video explaining how to code a strategy using 2 timeframe ? (Like HTF is having a signal, and then the confirmation is done on a LTF)
cheers
Not yet, I have something in mind and on my todo list, but it's only a matter of time and priority.
@@CodeTradingCafeLooking forward for such strategies with 2 time frame analysis.
congratz for your work.all best.
Thank you for your support!
Thank you for the video! Do you think this signal can be used for machine learning?
Thank you for your support, we could try it but I am afraid it might add noise to the current state of the signal. But there is only one way to find out :)
ya you can use it for blockchain too
Really nice , can you make a video on opening range breakout strategy
Thank you, yes I will add it to a long list, but meanwhile if you are in a hurry this can be done by adapting the current video with some modifications, just compute the support let's say on the first couple of hours of the day (opening hours).
Thanks you i m for Morocco i love your videos
Thank you Khalid for your support! Beautiful country :)
@@CodeTradingCafe welcome to Morocco in any time bro i have a simple question in code modul Lstm the day interval i have problems i have trede losses i have changed in 1 h interval for your opinion is God for to work of the module if yes a must change something als in the code for adapter with 1 h interval.thank you very much
Hi, honestly I tried LSTM for trading and all I can say is that it doesn't work well, if you're doing it for education purposes then it's good but for trading it's not as good.
@@CodeTradingCafe thanks you very much yes i want to try with demon account and si how it worksk. The last question what the perfect time the run the code in beginning of open the Marchés ?
I think the algos work well during the US session
"zone might change". Thats the whole point. Tried using atr? Using the fraction of the range between 2 zones?
No haven't tried with ATR but the idea is to define a max zone width, I think out of experience a trader can somehow set it for a given asset.
Thanks brother, Wonderful Code
You are welcome, I am glad it's helpful. Thank you for your support.
Great video! Can you code for Darvas Box?
Sure we can, but in my opinion it's almost the same as break out pattern strategy.
Well done
Thank you, glad you liked it!
I like to ask you these two questions:
1. How does this strategy avoid fake breakouts?
2. How do you scan to find symbols to trade this strategy on?
So far we don't avoid fake breakouts we just deal with them in trade and risk management. Symbols I just try on different assets and see where it works.
I am just working on a scanner to scan my broker's 900 symbols for strength and weakness to get a short watchlist around 10 assets for different strategies i.e MACD, RSI, Advance/Decline or so but i'm not shure what's the best strategy to scan for.
Thank you for this content !
Now you detected the break of structure, how do you code the trade part ?
probably next video :)
thanks dear , it's cool
I'm glad you like it, thank you for your support.
What development environment are you using?
Python, the editor is VScode
What code editor you are using?
VScode Microsoft
Awesome!Is it easy to convert this code to javascript?
Thank you, I guess so, I think try to use chatGPT slicing the code into small parts at a time, it might work for javascript.
Quick question about your Udemy course, do you cover how to put your code in a live environment? I mean, with a real broker. Thanks for the video!
I do but very briefly, it's actually also covered here on the channel for Oanda: th-cam.com/video/WcfKaZL4vpA/w-d-xo.html
Do you make a tradingview indicator for forex ?
Hi, sorry no tradingview just python and backtesting.
you are there great man for learn code, but i have request use yahoo for data
Hi thank you, Yahoo finance package yfinance for python is not supported anymore and some of the data I got was not reliable.
Great work, however, correct me if I'm wrong but in the isPivot function here:
for i in range(candle-window, candle+window+1)
Aren't we inserting lookahead bias for the pivot calculation by look ahead of the current candle? And shouldn't this be:
for i in range(candle-window, candle)
Just curious what the correct way is and why you calculated it that way. Thanks!
Hi, thank you for your support. You are absolutely right the function itself will cause a look ahead bias, however we used it in function detect_structure and there is a warning comment at the beginning of the function that the window parameter should be greater than the pivot window, so in other words we apply the isPivot function to candles that are in the past and we stop at currentcandle-window which should avoid the look ahead trap.
I hope this helps.
@@CodeTradingCafe Thanks for your response. I understand what you mean, however I have a different concern with this approach. Imagine using this in live trading, at that time you don't have the future candles for the isPivot function. In that case, even if you try to remove the lookahead bias through the detect_structure function, there won't be a correct way to detect pivots anyway so it won't matter. I tried to change this to detect pivots only using past data but that creates a lot of noise. However, afterwards I created a noise clearing function of my own and now it works rather nicely and the results still aren't perfect but they are closer to the original. Anyway, amazing content, your videos are very thought provoking and informative, keep up the good work 👍
Thank you for your feedback. I think in live trading we can only e test for pivots in the recent past the current candle is excluded of course, even the current 4 candles let's say are excluded. Glad you found a workaround, it's never easy... but we like it :)
what is the backtesting result for this strategy ?
As is not well, but it has to be combined with other indicators (mainly trend indicators) to provide good potential.
Good jon
Thank you!
Thank you very much Dr. really enjoy your work. Just wondering do you offer any private one-to-one consulting? If so, would you mind dropping me a message?
Hi, thank you for your support. I can try to help you through email, my email is in the about section of this channel.
@@CodeTradingCafe thank you so much for getting back to me. I did look at the about section but couldn’t find one. I just found links for the other courses.
Sorry, it's codingntrading gmail com
Very nice and informative video...But I have one query regarding that how we can use this code on daily basis for the breakouts...I mean it worked absolutely fine for previously loaded data but if we want the stocks or scripts from the collection of scripts..how we can optimize this script ???
Hi, thank you. We can use the function detect_pattern using different dataframes for different assets, the only modification is to move some parameters as input argument for the function because these will be asset dependent (like the zone width for example).
can we used this stratgy in live trade
You can, but this is one indicator you might want to combine it with another one for confirmation and of course a better trade management is crucial.
Can u give me the URL from the page, where u downloaded it. thx
3:30
it's Dukascopy bank they provide data as well.
Hi there. Another awesome video.
While playing with my data pivot points are very often placed on neighboring candles. I tried to get rid of this issue by increasing the pivot window, but it didn't work. The only solution I was able to implement was to disallow placing a pivot point if there is already one next to it. But I have a feeling that this is not the right solution. How else can I solve this situation?
Thank you for your support. The reason you may have 2 close pivots is because they might have the same extreme value (high or low) but the way you are proposing is also good just discard a pivot if one of the same level is very close, at the end you need one pivot placed in each "zone/area". Good luck!
Hi, I didn't really get where you downloaded the data from. I downloaded daily data from Yahoo finance for the same period and noticed that the data is actually quite different. Could you share the source with us? Thanks in advance!
Hi, you can try Dukascopy, or your broker.
I am not sure but it will be great if you can upload the source code as well in github since i cannot access google drive,blocked by my IT
How are you surviving without the codes! I definitely should set a git repo for this channel!
Hi
How to code to catch the breakout at the bottom?
thanks
You're welcome! thank you for your comment.
Hi ,Thank your for such a good pointing. After I have integrated MT5 to get real data. What i get from the function of 'isPivot' is always zero, hence when the code run towards the end of the coding, the return of function 'pattern detected' also become zero. I have tried a few way but still i get zero result. So could you point out what could be the cause of this? Thank you.
Hi, I suspect the number of windowed candles (window parameter) and the timeframe are not matching try changing the parameters decreasing the window to 1 for example, if the problem persists then there is a problem within the function, check for small bugs like the columns names, the casing (upper or lower first letters...). The funciton should return something even for real data.
i did what you have told, set data collection to H1, window = 1, 'is_Pivot' did return data. But not the 'pattern_detected' function. Could you please explain more why such parameter will return data. Thank you. On top of that, previously when i use df.tail() to check the 'is_Pivot' output. Although the ' is_Pivot' output show zero but the code manage to plot graph with pivot mark on candle. Why is that so? Thank you. @@CodeTradingCafe
Hi, at this point it's hard to debug online, but mainly the constants or hard coded values in the code they work for specific assets and timeframes if you change one you need to adjust the other.
What would be the value of zone_with and other parameters for 1 min data, im not getting any level breaks
It's hard to give a value this depends on the asset, check the charts it's easier to set a number visually.
hii
Does it connect to the Interactive Brokers system?
Currently no, but we can add the IB API functions to make it work.
Could you rewrite this to detect channel break. I mean now we can detect only breaking of horizontal channel (or price level). It's can be ok for the Forex, but not for the stock definitely.
Yes with a similar approach it can be rewritten for channels I can do it for the coming weeks/videos, might need some time though.
Already did a video about channel break out detection using linear regression no ?
Can you give a discount on Data Analysis With Pandas And NumPy In Python
course?
Sure www.udemy.com/course/data-analysis-with-pandas-and-numpy-in-python/?couponCode=7B9ACF76734A59AA0CB4
Good luck!
nice! are you making money with it?
Hi, thank you, no not this strategy, I don't run many strategies only few.
SMART MONEY
I agree, it's good, but also a bit overrated
i recomend you get the code then watch the video while adding your own comments in the code
Thank you, I agree, it's a good way to go through the session/video.
@@CodeTradingCafe IS there a way i can send you code built around your work am now to programing so i keep running into errors concering the table information being used for other parts of the code
Hi sir, i need Automatic trading bot for binomo platform based, 1min buy sell scalping strategy
Hi, I am not familiar with binomo I am not sure they provide a python API.
@@CodeTradingCafe fine I understand, I have a scalping strategy for binary options trading ( 1min buy and sell concept) , need a bit for auto trading, what can I do, how to search.
wow, you are very handsome
lol, thank you!
Not useful for real trade. Need Realtime signal generated from bunch of stocks list, not from just single stock. If you want to become profitable.
The same method/function can be cloned and used for as many stocks and currencies as needed, at the end it's the same algorithm that we can repeat... But I agree with you, I would change the function to make it applicable for live data instead of ready/historical data.
@@CodeTradingCafe one of the main challenges i have with your videos is 1) how with elegance to adapt a trading strategy for one stock to multiple stocks to make a scan. I usually cut the number of candles ex [-50:] but in this way could have more than one signal 2) adapt from forex to stock.As your channel is educational maybe could be appreciated a video where you explain how to address some daily jobs as the ones above. Personally instead of a fixed width i adapt with atr or bollinger to detect stocks breakout, because the difference between an high and the mean of the 3 points can be really variable depending by the level of price. Another solution would be to use a percentage. Thanks for the nice content
At least you do this basic part on your own, he has explained well about the algorithm on historical data. Those who understood the algorithm can refactor the code a bit to run on live candle data. 😂
Hi
I would like to create a bot, will you be able to do it?
@@vanaromHUOT still learning for proper strategy bot creation.
hi how to contact you
any telegram id ?
My email is in the about section, no telegram sorry, good luck!