# Something Interesting in Financial Video - page 31

MetaQuotes, 2023.04.13 14:56

Get the code at GitHub: https://github.com/jimtin/algorithmic_trading_bot

In this video tutorial, the presenter explains and implements the EMA cross strategy to build a trading bot to place trades automatically. The strategy involves using two EMAs, EMA 50 and EMA 200, and generates buy or sell signals when EMA 50 crosses over or below EMA 200, respectively. He also discusses stop loss, entry price, and take profit for each trade and how to create a separate function to design a library. The presenter updates the EMA cross strategy function to integrate with the get_data function created in a previous episode, and the indicators function returns all the necessary information to the calling function. The code is simplified by extracting the timeframe, making it easier to manage and maintain for algorithmic traders.

• 00:00:00 In this section of the video, the presenter explains the EMA cross strategy and how it works. He mentions that the strategy involves using two EMAs, specifically the EMA 50 and EMA 200, and how a Buy Signal is generated when the EMA 50 crosses above the EMA 200, indicating an upward trend, while a Sell Signal is generated when the EMA 50 crosses below the EMA 200, indicating a downward trend. He also talks about the stop loss, entry price, and take profit for each trade, highlighting that the stop loss is always the corresponding highest EMA, while the entry price is the high or low of the previously completed candle depending on the signal generated. Finally, he discusses how to extract and abstract away the strategy into a separate function to create a library.

• 00:05:00 In this section of the video, the presenter outlines a pseudo code of the steps involved in building a trading bot based on the EMA cross strategy. The first step is to retrieve the data, which can come from various sources. The function created for this purpose has two parameters, symbol and time frame. In this episode, the data is retrieved from MT5 using a library created in a previous episode that returns a data frame. The second step involves calculating the indicators, which for this strategy are EMA 50 and EMA 200.

• 00:10:00 In this section of the video, the focus is on updating the EMA cross strategy function to take advantage of the get_data function previously created. The first step is to retrieve the data by creating a variable and using the get_data function to store the data in it. The second step involves calculating the EMA indicators and EMA cross, which is done by creating a function called calc_indicators that takes a data frame and calculates the EMA 50, EMA 200, and EMA cross. This algorithm is designed in such a way that it can easily be updated to work with different exchanges in the future. The data frame is passed to each of the EMA calculators and EMA cross calculators, and the resulting data frame with all the necessary information is returned to the function. This data is then used to update the EMA cross strategy function before being added back into the main.pi file.

• 00:15:00 In this section, the presenter updates the indicators function to return all the information back to the calling function. The updated function can be used over and over again, making it easier to manage the code. The presenter imports the EMA cross strategy into Main and passes in the symbol, time frame, and EMA values to see what comes out. The code is simplified by extracting the time frame, making it easier to manage, typically breaking down less and ultimately making the life of an algorithmic trader a lot easier.

MetaQuotes, 2023.04.13 14:58

Get the code at GitHub: https://github.com/jimtin/algorithmic_trading_bot

The video tutorial teaches how to create an EMA cross detector using Python, discussing the process of creating two different EMAs and identifying potential trends in the market, and walking through how to construct the EMA crossover detector function. The function creates two new columns, position and pre-position, and checks whether a cross event has occurred to create a column that sets True if a crossover has occurred; it also demonstrates how to use the EMA cross detector in main.py by extracting only the rows that have a true crossover event. The tutorial also hints at the next episode where it will demonstrate how to calculate a personal EMA cross strategy.

• 00:00:00 In this section, the video tutorial discusses the process of creating an EMA cross detector using Python. The host advises having the ability to calculate exponential moving averages (EMA) and the pandas library installed. An EMA cross involves plotting two different EMAs on a chart to identify potential trends in the market. To use an EMA cross strategy, a shorter-term EMA and a longer-term EMA are plotted, and when the shorter-term EMA crosses above the longer-term EMA, it's a bullish signal, and when it crosses below, it's a bearish signal. The tutorial then proceeds to walk through how to construct the EMA crossover detector function, which accepts three different variables, and advises the importance of commenting code as you work through it.

• 00:05:00 In this section, the speaker explains how the EMA cross detector works by creating two new columns called position and pre-position. By comparing the two EMA columns, the function checks whether a cross event has occurred, and then creates a column that sets True if a crossover has occurred, and False for everything else. The function also utilizes numpy and a Lambda function to quickly perform these operations, and then removes the position and pre-position columns before returning the EMA detector results to the user. The speaker then demonstrates how to use the EMA cross detector in main.py by extracting only the rows that have a true crossover event.

• 00:10:00 In this section, the speaker shows how to extract true values from the EMA cross data frame by setting the EMA cross true variable, print them to the screen, and create an EMA cross trading bot. Furthermore, he hints at the next episode where he will demonstrate how to calculate a personal EMA cross strategy.

MetaQuotes, 2023.04.13 15:01

Get the code at GitHub: https://github.com/jimtin/algorithmic_trading_bot

This video discusses how to build a lot size calculator function for a trading bot on Metatrader5 using Python. The function requires knowledge of the balance being risked, risk amount, stop-loss price, entry price, and the symbol being traded, and differs for Forex trading. The speaker emphasizes the importance of rounding values to prevent Metatrader5 from rejecting the calculation and shows how to add a different currency to the function. They also discuss adding in the exchange rate, making the code more robust by adding a catch-all else statement, and providing a standard calculation for pip size and pip value. The next part of the series will focus on safely and efficiently placing orders on Metatrader5.

• 00:00:00 In this section, the presenter explains the steps involved in building your own Metatrader5 Python trading bot, starting with the creation of a lot size calculator. He advises that to calculate the lot size, one needs to know the stop loss, stock price, balance, and risk amount. The presenter recommends previous episodes on his channel for more information on understanding stop loss and stock prices, as well as on using a strategy to calculate signals. The other three episodes following the lot size calculator would help traders to place orders on Metatrader5 safely and efficiently. The presenter emphasizes the importance of creating a pseudo Library function for the lot size calculator, giving code explanations for each step.

• 00:05:00 In this section of the video, the instructor discusses the steps to build a lot size calculator function for a trading bot. He explains that the function requires knowledge of the balance being risked, the risk amount, stop-loss price, entry price, and symbol being traded. The lot size calculation differs for Forex trading and requires the calculation of pip size and pip value. The instructor provides an example of how to calculate the amount to risk and the pip value for USD/JPY currency pair. Finally, he suggests using the current exchange rate for the entry price instead of querying the mt5 for the exchange rate.

• 00:10:00 In this section, the video explains how to calculate lot size and the importance of rounding values when presenting the lot size to Metatrader5. The speaker highlights how presenting large decimal values can result in Metatrader5 rejecting the calculation and how rounding to two decimal places can help. However, using the lot size calculator with very small balances can present issues due to the rounding effect. The speaker recommends trading with a larger lot size or accepting that risk calculations may be skewed. The video also briefly shows how to add a different currency, such as the Canadian dollar, to the function.

• 00:15:00 In this section, the speaker discusses adding in the exchange rate, determining the raw lot size, and making the code more robust by adding a catch-all else statement. They caution against using the catch-all else statement too liberally and suggest only trading symbols that have been thoroughly researched. The speaker also provides a standard calculation for pip size and pip value and hints at placing orders in the next part of the series.

MetaQuotes, 2023.04.13 15:06

Get the code at GitHub: https://github.com/jimtin/algorithmic_trading_bot

This video tutorial demonstrates how to build a Python trading bot in MetaTrader 5 that will never miss a Candlestick. The code initiates MetaTrader 5, captures current and previous times, and utilizes a while loop to retrieve a single candle and compare to the previous candle to identify new candlesticks. The video emphasizes the importance of correcting spacing in the code, implementing a sleep function to prevent crashing, and utilizing a separate function to simplify the main function. The instructor also provides guidance on how to handle errors in the code and use print statements for clear testing.

• 00:00:00 In this section of the video, the presenter shows how to monitor Metatrader5 to ensure that your trading strategy does not miss any new Candlesticks. The code used is straightforward, with a startup function used to initiate MetaTrader5, and variables set up to capture the current and previous times. A while loop is used to keep the trading function running as long as it is true, and the code retrieves a single candle using the timeframe for the strategy and compares the current time with the previous time. If values are not equal, a new Candlestick has occurred, and a check is implemented to see if a trade needs to occur before implementing the trade. The BTCUSD currency pair is used to get the current time, as it trades 24/7, and the time is assigned to the current time variable.

• 00:05:00 In this section, the video discusses the importance of updating the spacing in the code to ensure that all tabs are in line. The code checks if there is a new candle and if there is, it runs it through the strategy to see if a trade needs to occur. The video also mentions the use of `time.sleep(1)` to prevent high CPU usage and program crashing. The main function is then cleaned up by pulling out the symbols and time frame to create a separate function, `run strategy`, that allows for passing the strategy in at any given time while simplifying the main function. Lastly, the video discusses the process of extracting the symbols that the strategy applies to and the time frame used for trading, while keeping the time frame in main for polling of MT5 to get new candles.

• 00:10:00 In this section, the instructor explains how to handle errors in the code when building a trading bot using Python in MetaTrader 5. The video shows how to use the MetaTrader 5 library and the Strategy library to deal with error handling in the code. A "true" value is returned if the strategy was successfully run, while "false" is returned if no trade occurs, indicating that no order has been placed on MetaTrader 5. Additionally, the instructor suggests using a print statement to make the testing process clearer and easier to understand for the user.

MetaQuotes, 2023.04.13 15:13

### Build Your Own MACD Crossover Strategy with MetaTrader 5 and Python

Get the code at GitHub: https://github.com/jimtin/algorithmic_trading_bot

This video provides a comprehensive guide on how to create a MACD crossover strategy using Python and MetaTrader 5. The process involves obtaining OHLC data, calculating indicators, generating signals, and developing a function for crossovers that can be used with different technical indicators. The presenter emphasizes the importance of backtesting before using the strategy in live trading and provides code and resources for quick implementation. The video also covers calculating values for sell signals, updating data frame values, and filtering results for easier backtesting. Overall, the video is a great resource for traders interested in developing and implementing a MACD crossover strategy.

• 00:00:00 In this section of the video, the presenter outlines the necessary tools needed to create a MACD crossover strategy using Python and MetaTrader 5. The MACD indicator is made up of three separate pieces of information: the MACD line, the MACD signal line, and the MACD histogram. For this strategy, the focus is on the MACD line and the MACD signal line, crossing each other to generate buy and sell signals. The presenter provides an outline of how to create a strategy, defining a function that brings all the necessary pieces together and specifying inputs such as the symbol, time frame, and MACD inputs. The presenter also emphasizes the importance of commenting as a way to make an investment that will save unnecessary time in the future.

• 00:05:00 In this section, the instructor discusses the steps involved in developing a MACD crossover strategy on MetaTrader 5 using Python. The first step is to obtain the OHLC (open, high, low, close) data for the chosen symbol, time frame, and exchange. Then, the MACD indicator and another indicator (not specified) are calculated based on input values for the MACD fast, slow, and signal. Next, the signals are generated using the indicators and arbitrary values for rules. The instructor advises against using these values for live trading without backtesting. Finally, if desired, an auto trading bot could be created to execute trades based on the generated signals.

• 00:10:00 In this section, the speaker explains the importance of retrieving an adequate number of candlesticks when using EMAs in a trading strategy. A rule of thumb is to retrieve at least five times the number of the EMA being calculated. If the exchange being used has a limit on the number of candlesticks that can be retrieved, this may impact the use of certain EMA values in backtesting. Additionally, the speaker walks through the process of calculating the MACD indicator using ta-lib and explains that a simple crossover indicator needs to be built into the strategy to identify when the MACD line and signal line cross each other.

• 00:15:00 In this section of the video, the presenter explains how to create a generic crossover function that takes any two columns of a data frame and tells when they cross each other. By using this function, traders can easily use different technical indicators with crossing mechanisms. The function creates two additional columns on the data frame that compares them together. Once a cross has been identified, a third column is added, leaving only the new cross column. The presenter emphasizes the importance of dropping NA values and using in-place equals true to ensure the function is fast when doing algorithmic trading. Traders can access the code on the Algorithmic Trading Bot Github page https://github.com/jimtin/algorithmic_trading_bot.

• 00:20:00 In this section, the video covers the calculation of signals for the MACD crossover strategy. The function takes in a data frame and allows users to customize the take profit, stop loss, and buy/sell prices. The function starts by adding columns for order type, stop price, stop loss, and take profit, which serve as placeholders for trades that haven't been made. The function then iterates through each line of the data frame and checks if there is a crossover, indicating that a trade needs to occur. If there is a crossover, the function checks if the MACD line is above or below the signal line to determine the direction of the trade, which is indicated by a signal value of either 1 or -1. The function then returns a data frame with the buy and sell signals for easy backtesting and review.

• 00:25:00 In this section, the speaker explains how to calculate values for a sell signal in the MACD crossover strategy using Python and MetaTrader 5. After the cross happens and MACD goes below the signal, it is an indication to sell, which means the price is about to or is already going down. Hence, the order type is set to buy stop, stop price to the high of the previous candle, and stop loss to the low of the previous candle. The take profit is set to a one-to-one ratio. For a sell signal, the opposite parameter values are used, i.e., stop loss is set to the high of the previous candle, sell stop to the low of the previous candle, and take profit at a one-to-one ratio.

• 00:30:00 In this section of the video, the speaker discusses updating the values in the data frame of the MACD crossover strategy. They note that while the previous code took care of when the signal was equal to 1 or negative one, the vast majority of the time, it's going to be equal to zero, leading to potential errors. To avoid any errors, they add default values back in for when there is no order type, stop price, stop loss, or take profit value. Additionally, the speaker notes that if the very first row of the data frame is the one that generates a true value, then there is no minus one to do to get there, which could lead to further errors. To address this issue, a simple function is written to skip the very first row of the data frame.

• 00:35:00 In this section, the presenter explains that the existing code in the main function of the Python script calls a few start-up functions and imports the MACD crossover strategy. He proceeds to update the main function to use the ETH/USD currency pair with a one-hour timeframe and prints it to the screen. However, since there are a lot of instances where nothing happens, he suggests filtering the results to only print the values that are true to make it easier to backtest the strategy. The video then shows how the code can be modified to achieve this.

MetaQuotes, 2023.04.13 16:46

### Building a web application using Python and Metatrader 5 with Streamlit

Building a web application using Python and Metatrader 5 with Streamlit

This video demonstrates how to create a real-time chart using Python, Streamlit, and Metatrader 5 that displays currency exchange rates and offers zoom and timeframe options. The presenter uses Pandas for importing data frames and Plotly to plot data, adding functions to calculate moving averages and Relative Strength Index. The video includes threading to handle zooming and keyboard shortcuts for interactivity. The presenter concludes the video by explaining the code's different functions and adding functionality to draw objects on charts, sharing the code in the app's description. The tutorial offers beginners a simple introduction to building real-time financial charts.

• 00:00:00 In this section, the video's creator showcases a real-time chart built using MetaTrader 5, Python, and Streamlit. The chart displays currency exchange rates and offers features to zoom in, zoom out, and switch between timeframes. The Python code uses the Streamlit and MetaTrader 5 libraries, along with Pandas for importing data frames and Plotly for graphing. The chart includes functions to calculate the moving average and Relative Strength Index with adjustable parameters for users. The creator also includes threading to handle zooming and keyboard shortcuts for user interactivity. Overall, the tutorial offers a beginner-friendly introduction to using these libraries for building real-time financial charts.

• 00:05:00 you want to build a web application using Python and MetaTrader 5 with Streamlit, you will need to call specific functions to provide the necessary data. To get the symbols, you can use the "metatrader" function to extract their names and then return them in a dictionary format. The set package configuration function allows you to customize the layout of the web application, such as the window size and title. Additionally, in order to calculate the lsi (relative strength index), you must provide the function with the necessary data and parameters, such as the data frame and rsi value, which can then be plotted.

• 00:10:00 In this section, the speaker explains how he created global variables and added the LSI calculation to the data frame, and appended the trace so that the RSI values can be shown on the chart. He also shows how he created the infinite loop function, which updates the chart every second, using the time frame, symbol, bars, moving average, and LSI values. The time frame is obtained from a dictionary and the bars are obtained using the mt5.copy_rates_from_pos() function. The chart is not an image but an animation that is constantly being updated every second.

• 00:15:00 In this section, the presenter explains how to convert bars data frame to be reduced later on and how to convert time into seconds for better readability. The section also covers using a scatter chart and how to calculate the moving average to plot it to the chart. The presenter updates the figure layout with a fixed range and paper color to have the chart fixed in place and to better present the data to the user.

• 00:20:00 In this section, the speaker explains how they made adjustments to the size of the window and the x-axis to eliminate gaps in the daily chart. They also add a horizontal line of the last price using a simple
line of code. The speaker then demonstrates the on press key function which shrinks or grows the chart when the user presses the minus or plus key. The code includes multiple functions and placeholders to keep the application simple and easy to navigate.

• 00:25:00 In this section, the speaker explains the code for initializing the connection between Metatrader5 and the chart, and the use of a keyboard listener thread to adjust the size of the chart using the plus and minus keys. They also discuss the use of the `st.title` function and the creation of two columns for the sliders and options through the `st.connect` function. The speaker explains the use of a placeholder for column one and the selection of a moving average through the `sd.selectbox` function. They also mention the availability of options for choosing the stock symbol or pair, as well as the time frame.

• 00:30:00 In this section, the YouTuber concludes the demonstration of building a web application using Python and MetaTrader 5 with Streamlit. They explained that the app displayed information about trading signals and added functionality to draw objects on the charts. They also pointed out the different functions and their purposes in the code, ending with sharing the code in the app's description. The YouTuber thanked their viewers for watching and concluded the video.

MetaQuotes, 2023.04.13 16:54

### How to import stock price data from MetaTrader 5 into Python?

How to import stock price data from MetaTrader 5 into Python?

In this YouTube video, different methods to import stock price data from MetaTrader 5 into Python are explained. The methods include importing necessary libraries, setting the desired time frame and time zone, defining a function called "get data," manipulating the resulting data frame, using the tqtndm package, creating a rates frame, and utilizing two data frames to retrieve prices and date/time information. The speaker suggests putting the loops into a function to make the code cleaner, and using these methods, users can easily import data for numerous symbols without much difficulty.

• 00:00:00 In this section, the speaker explains how to import stock price data from MetaTrader5 into Python. The first step is to import all the necessary libraries, including pandas, pytz, datetime, tqdm, and MetaTrader5. Then, the speaker initializes MetaTrader5 and sets the desired time zone and time frame. The speaker defines a function called "get data" that requires the symbol, the number of candles needed, and the time frame. The function returns the desired data, and the speaker explains what each input and output does in the function.

• 00:05:00 In this section, the speaker explains a function used to import stock price data from MetaTrader5 into Python. The function takes in a symbol, a time frame, and a date, and returns a data frame containing the requested data. The speaker goes through steps to manipulate the resulting data frame, including converting the time column to daytime and dropping unnecessary columns. Additionally, the use of a for loop is suggested to make it easier to call data for multiple assets.

• 00:10:00 In this section, the speaker explains how to import stock price data from MetaTrader5 into Python using the tqtndm package. They use the try function and accept function to call a rates function previously defined that takes in the symbol and the number of days set to 400. The returned data is appended to a dictionary, and any not available data is dropped. The speaker suggests putting the loop into a function to make the code cleaner. Overall, the process involves creating a rates frame, appending the data to a dictionary, and then running the script.

• 00:15:00 In this section, the speaker explains that with the use of two data frames, users can easily import stock price data from metatrader5 to Python by retrieving the prices and date/time information. This method can be used for numerous symbols without much difficulty.

MetaQuotes, 2023.04.13 17:12

### How to create Algorithmic Trading Strategies with Python - Step by Step Process

How to create Algorithmic Trading Strategies with Python - Step by Step Process

The video provides a step-by-step guide on how to create algorithmic trading strategies using Python. The first step involves defining the rules for the system, eliminating emotions from trading, and conducting backtesting to optimize profitability. The presenter then demonstrates how to create a trading strategy using a hypothesis and technical indicators such as moving average crossovers. The strategy is then coded, and backtesting is conducted repeatedly to ensure optimization. The second section focuses on coding the algorithmic framework and creating a signal function that determines whether to buy or sell based on a comparison of simple moving averages. The third section discusses how to process live market data using functions, while the fourth describes how to deploy the strategy on WPS. The presenter concludes by advising beginners to keep their trading strategies simple and clear.

• 00:00:00 In this section of the video, the presenter explains the process of creating algorithmic trading strategies with Python. Firstly, they define algorithmic trading as a system with explicitly defined rules and no exceptions. The advantages of this are that we can code trading strategies based on quantifiable data and emotions are taken out of the equation. They also mention that backtesting is easily done to optimize and test the system's profitability. Next, the presenter shows how to create a trading strategy by using a hypothesis and technical indicators, particularly moving average crossovers. With the information gathered, set of rules are created, and then the strategy undergoes backtesting. This process can be repeated until the strategy is deemed optimal.

• 00:05:00 In this section, the speaker discusses the step-by-step process of creating algorithmic trading strategies with Python. They explain how backtesting allows traders to understand how their profit and loss is developing, and if successful, traders may move on to a forward test with a live trading bot on a demo account. The speaker also recommends using Python for trading as it is an easy language to learn and has many libraries for backtesting and algorithmic trading, such as pandas and plotly. Finally, the speaker walks through the process of creating a simple moving average crossover strategy on the German stock index, using a fast moving average of 10 and a slow moving average of 100. They emphasize the importance of coding the algorithmic framework, which can be found on their GitHub page.

• 00:10:00 In this section, the presenter demonstrates how to use Python to create an algorithmic trading strategy using the moving average crossover strategy previously discussed. They provide two files: a backtested file and a live trading bot file. The backtested file includes data analysis of how the strategy performed for the year 2032. The live trading bot file requires the creation of a file with login credentials and allows users to trade using moving average crossovers. The presenter then shows their Python integrated development environment and explains the code, which uses libraries such as pandas, blockly, and datetime to retrieve historical data, calculate simple moving averages, and apply trading logic. Finally, the presenter creates a signal function that determines whether to buy or sell based on the comparison of the simple moving averages.

• 00:15:00 In this section, the speaker explains the process of calculating the signal column that would indicate when to buy or sell a particular security. The signal column is derived by applying the "get signal" function to the data frame bars, which then checks row by row if the conditions for buying or selling are met. Additionally, the previous price change and signal change columns are also calculated to determine the hypothetical profits, taking into account the trade volume and the commission paid to the broker. The speaker then shows a plot using the gross and net profits over a six-month period, demonstrating that the strategy produced a net profit of €2,380, with some drawdown periods. Finally, the speaker mentions sharing sample code of the backtesting strategy in case the viewer wants to test it themselves for a longer history.

• 00:20:00 In this section, the presenter explains how to process live market data using functions to create a trading strategy in Python. They suggest importing MetaTrader5, pandas, time, datetime, and account principles with the default parameters of their strategy. The presenter created functions for trading to close positions and check the trading hours of London and New York sessions. They also created a function to send a market order using a trading signal in the loop, and if the fast SMA is above the slow SMA, they suggest closing the sell positions. The presenter demonstrates how to use these functions and check the number of open positions with the MT5 Positions Total function to provide an overview of the account when logging into the trading account.

• 00:25:00 In this section, the speaker explains the final step of the process which is deploying the strategy on WPS (Web Processing Service). He suggests using a DP (Cloud Desktop Provider) called Countable, to which he provides basic configurations. He also notes that MT5 only works on Windows and recommends selecting a UK hosted data center if the broker is located in London. The speaker then proceeds to give tips and recommendations to beginners, advising them to keep their strategies simple and clear, in order to later add on more over time. He concludes by thanking the viewer and encouraging them to ask questions in the comments.