<?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 Sebastian Ospina Valencia on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Ospina Valencia on Medium]]></description>
        <link>https://medium.com/@elospieconomics?source=rss-c591bb4560cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8PN0dVbEjpUZ1HjN</url>
            <title>Stories by Sebastian Ospina Valencia on Medium</title>
            <link>https://medium.com/@elospieconomics?source=rss-c591bb4560cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:07:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elospieconomics/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[The Real Job of a Quant: Portfolio Building and Management]]></title>
            <link>https://medium.com/@elospieconomics/the-real-job-of-a-quant-portfolio-building-and-management-3344367e8bbf?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3344367e8bbf</guid>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 15:45:07 GMT</pubDate>
            <atom:updated>2024-12-20T15:45:07.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BH_0yrEFqrVYEmSqRtu2g.jpeg" /></figure><p>In this article, I will set myself apart from the content I traditionally write here because of the misunderstanding of what a quant does most of the time. Most people think that a quant is always developing HFT strategies or some quant rocket science stuff to make millions in one single trade but there is nothing most far from the truth than that statement.</p><p>The truth is that most of the time a quant is dealing with the question of how to maximize the returns while minimizing the risks faced to get those returns, and day trader, this is for you, is not just setting a stop loss or take profit, is far beyond from that! Dealing with risk consists of how you <strong>strategically allocate</strong> your capital to a series of strategies or capital instruments.</p><h4><strong>The Theory in Plain English</strong></h4><p>I will try to explain the theory behind portfolio building in simple words so, in future next article, we can do the portfolio optimization using Python. So imagine you have two stocks that will yield the next returns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRe1uTrZgKxNTPMiTX-dPQ.png" /></figure><p>The question for you is will you prefer to invest all your money in asset 1 or all your money on asset 2? If you invest in asset 1 you will get a lot of returns at the end of the period but with a lot of pain, in some moments you will be very worried for your money, but asset 2 is too boring it barely changes over time. So returning to the first question, probably your answer will be another question: could I invest in both at the same time? and the answer (if you are not crazy to invest all in asset 1 or too annoying to invest in asset 2) will be yes! sure! because when doing that you could combine the stability of asset 2 with the high returns of asset 1 or, in other words, by investing in both assets you are getting the best of two worlds but things start to get complicated from here because How do you combine the assets to get the best of the two worlds?</p><p><strong>The Markowitz trick</strong></p><p>There is a statistical model named Markowitz proposed by Harry Markowitz that mathematically allocates the capital in each asset in order to maximize the returns while reducing their volatility. The trick is to select assets that don’t behave similarly (uncorrelated) and this is key because if the two assets behave similarly, when you lose on one asset you will lose in the other too meanwhile if they do not behave similarly, when one loses, the other one might get earnings or at least don’t lose. The magic is that doing this is that you can increase your earnings while your risk is smoothed.</p><p>If you have got to here, you probably are wondering “<em>ok, but how do I select the assets of my portfolio?”</em> I will not answer this in-depth because the answer is not trivial, there are a lot of methods that maybe in the future we will discuss but the essential trick remains: Select assets that do not behave similarly. Here is a small example of using correlation to select stocks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*KIFXd4Vp2SPp5soV1SYu8Q.jpeg" /></figure><h4>The Quant question</h4><p>Now that you know what a portfolio is and the core insights of how to build it, the job of a quant is to determine, quantitatively, when and how many times to perform the asset selection process, how many times and when to rebalance the selected assets. These are the real discussion of quants that goes beyond setting a stop loss and a take profit.</p><p>I hope with this small article you have learned a little bit of portfolio management and what a quant do. If you want to see more content follow me on instagram @thequant_trader</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3344367e8bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5 : Modifying Open Trades]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-modifying-open-trades-8622d31632f3?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8622d31632f3</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading-bot]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 02:34:17 GMT</pubDate>
            <atom:updated>2023-08-06T02:34:17.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithmic Trading with Python and MT5 : Modifying Open Trades</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*apEwd1TOu0LVAZo_zzqwNw.png" /></figure><p>One essential feature that almost any trading robot has within its logic is to modify the opened trades: Modify the stop loss (to make a trailing stop, or to send to break even) and modify the take profit. So in this small post, we will see how to build a simple, but flexible function that allows us to do that with Python.</p><p>Imagine you have several trades opened some of them are longs (buy operations) and others are short (sell operations) some of them, have take profits (TPs)or stop loss (SL) and others have both, so our function must take into account all the cases. For this reason, our python function has to take into account the symbol of the trade, the unique identifier of the trade, the stop loss, and the order type.</p><p>We can express the previous paragraph in this line of code</p><pre>def modify_orders(self, symb: str,ticket:int,stop_loss:float = None,take_profit:float = None,type_order = mt5.ORDER_TYPE_BUY) -&gt; None:</pre><p>After defining the parameters of the function we can start to build the logic within this function based on the cases I previously mentioned to you: a tarde with a TP a trade with a SL and a trade with both. note that this function takes as an argument the type of trade and hence we made the function less complex. So we have only to worry about if the trade we are analyzing has TP, SL, or both and for that are the if, elif, and else lines that are into the function</p><pre>def modify_orders(self, symb: str,ticket:int,stop_loss:float = None,take_profit:float = None,type_order = mt5.ORDER_TYPE_BUY) -&gt; None:<br><br>        if (stop_loss != None) and (take_profit == None): <br>            modify_order_request = {<br><br>                &#39;action&#39;: mt5.TRADE_ACTION_SLTP,<br>                &#39;symbol&#39;:  symb,<br>                &#39;position&#39;: ticket ,<br>                &#39;type&#39;: type_order,<br>                &#39;sl&#39;: stop_loss,<br>                &#39;type_time&#39;: mt5.ORDER_TIME_GTC,<br>                &#39;type_filling&#39;: mt5.ORDER_FILLING_FOK<br>                                    }<br><br>            mt5.order_send(modify_order_request)<br><br>        elif (stop_loss == None) and (take_profit != None): <br>            modify_order_request = {<br><br>            &#39;action&#39;: mt5.TRADE_ACTION_SLTP,<br>            &#39;symbol&#39;:  symb,<br>            &#39;position&#39;: ticket ,<br>            &#39;type&#39;: type_order,<br>            &#39;tp&#39;: take_profit,<br>            &#39;type_time&#39;: mt5.ORDER_TIME_GTC,<br>            &#39;type_filling&#39;: mt5.ORDER_FILLING_FOK<br>                                    }<br><br>            mt5.order_send(modify_order_request)<br>        <br>        else:<br>            modify_order_request = {<br><br>            &#39;action&#39;: mt5.TRADE_ACTION_SLTP,<br>            &#39;symbol&#39;:  symb,<br>            &#39;position&#39;: ticket ,<br>            &#39;type&#39;: type_order,<br>            &#39;tp&#39;: take_profit,<br>            &#39;sl&#39;: stop_loss,<br>            &#39;type_time&#39;: mt5.ORDER_TIME_GTC,<br>            &#39;type_filling&#39;: mt5.ORDER_FILLING_FOK<br>                                    }<br><br>            mt5.order_send(modify_order_request)</pre><p>You can see that inside each if else statement there is a dictionary that is written like MQL code (remember to read this <a href="https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-the-only-mql-you-need-to-know-c9f15353fb4d">post</a> ) and note how that dictionary varies if the variables TP or SL are none, one last thing to mention is that in the case that both the SL and TP are none, we are going to modify the position with an SL and TP.</p><p>With this function, now we can start to think about how to develop a trailling stop… But that is for another story</p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18 or in </em><a href="https://t.me/TheQuantitativeTrader"><em>telegram</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8622d31632f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Building a Statistical Trading Robot Part II]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-building-a-statistical-trading-robot-part-ii-153729782d61?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/153729782d61</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 22:37:05 GMT</pubDate>
            <atom:updated>2023-07-23T22:37:05.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*BhpsZ1rregaznVAirAitAQ.jpeg" /></figure><p><strong><em>RISK DISCLAIMER:</em></strong><em> </em><strong><em>USE THE CODE AT YOUR OWN RISK</em></strong><em>. I WILL BE NOT RESPONSIBLE FOR YOUR FINANCIAL DECISIONS. DO NOT TRADE ON THINGS YOU DO NOT UNDERSTAND WELL. TRADE ONLY WITH MONEY THAT YOU CAN AFFORD TO LOSE.</em></p><p>In the last post, we talk about the pseudo-code of a bot that uses a linear regression as a statistical momentum indicator (haha sometimes the names are nice) if you haven’t read the post here’s the <a href="https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-building-a-statistical-trading-robot-part-i-c343e74758d6">link</a>. If you have already read that post it is time to code!</p><p>First, we will review, and define, the necessary functions for the bot in the next lines of code:</p><pre>import pandas as pd<br>import numpy as np<br>import MetaTrader5 as mt5<br>import  datetime<br>import pytz<br>from regressors import stats<br><br><br>#Function to extract the data<br><br>def extract_data(symbol,num_candles,time_frame):<br>    rates = mt5.copy_rates_from_pos(symbol,time_frame,0,num_candles)<br>    rates_frame = pd.DataFrame(rates)<br>    rates_frame[&#39;time&#39;] = pd.to_datetime(rates_frame[&#39;time&#39;], unit = &#39;s&#39;)<br><br>    return rates_frame</pre><p>In these moments we only need this function. Then as we see in the previous post, we are going to calculate the linear regression with the closing prices using <em>sklearn</em> to do that.</p><pre>data = extract_data(symbol,10,mt5.TIMEFRAME_M1)<br>y = data[[&#39;close&#39;]]<br>data[&#39;minutes&#39;] = range(10)<br>X = datos[[&#39;minutes&#39;]]<br><br>model = LinearRegression().fit(X,y)<br><br>slope = model.coef_<br><br>coef_pvalue = stats.coef_pval(modelo,X,y)</pre><p>Above is the code to calculate the regression and extract the slope and the significance value of that coefficient. So, first, we extract the last 10 candles of 1 minute from the EURUSD using the function of extract_data. Note that I choose 10 randomly, we will talk about that later, then I define the X vector as the range of numbers between 0 and 10. After that, we use the <em>LinearRegression()</em> function to fit the regression.</p><p>With the regression fitted, we could calculate the coefficient with model._coef and finally, we use <em>stats.coef_pval() </em>to get the list of the p_values or significance level of the slope coefficient. We have everything calculated now! Then we can build the robot!</p><pre>if slope &gt; 0 and coef_pvalue[1] &lt; 0.05:<br>  buy= {<br>        &quot;action&quot;: mt5.TRADE_ACTION_DEAL,<br>        &quot;symbol&quot;: symbol,<br>        &quot;volume&quot; : 0.05,<br>        &quot;type&quot; : mt5.ORDER_TYPE_BUY,<br>        &quot;magic&quot;: 202304,<br>        &quot;comment&quot;: &#39;MR&#39;,<br>        &quot;sl&quot; : mt5.symbol_info_tick(symbol).ask - mt5.symbol_info_tick(symbol).point*300,<br>        &quot;tp&quot; : mt5.symbol_info_tick(symbol).ask + mt5.symbol_info_tick(symbol).point*300,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC<br>    }<br><br>  mt5.order_send(buy)<br>        <br>if slope &gt; 0 and coef_pvalue[1] &lt; 0.05:<br>  sell= {<br>        &quot;action&quot;: mt5.TRADE_ACTION_DEAL,<br>        &quot;symbol&quot;: symbol,<br>        &quot;volume&quot; : 0.05,<br>        &quot;type&quot; : mt5.ORDER_TYPE_SELL,<br>        &quot;magic&quot;: 202304,<br>        &quot;comment&quot;: &#39;MR&#39;,<br>        &quot;sl&quot; : mt5.symbol_info_tick(symbol).bid + mt5.symbol_info_tick(symbol).point*300,<br>        &quot;tp&quot; : mt5.symbol_info_tick(symbol).bid - mt5.symbol_info_tick(symbol).point*300,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC<br>    }<br><br>  mt5.order_send(sell)</pre><p>And just in these few lines of code, we build a regression bot that sends trades if there is statistical evidence that the market has momentum. But this robot is far to be finished: We need to choose the optimal value for the timeframe ( 1 minute, 5 minutes, etc), and the range of the candles for the regression (10, 20, 30, 100, etc) and also the distances for the take profit and the stop loss. But that is for another story!</p><p><em>Do you have a strategy and want to automatize using any language you want while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=153729782d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Building a Statistical Trading Robot Part I]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-building-a-statistical-trading-robot-part-i-c343e74758d6?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c343e74758d6</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 03:38:28 GMT</pubDate>
            <atom:updated>2023-07-06T03:38:28.315Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>RISK DISCLAIMER:</em></strong><em> </em><strong><em>USE THE CODE AT YOUR OWN RISK</em></strong><em>. I WILL BE NOT RESPONSIBLE FOR YOUR FINANCIAL DECISIONS. DO NOT TRADE ON THINGS YOU DO NOT UNDERSTAND WELL. TRADE ONLY WITH MONEY THAT YOU CAN AFFORD TO LOSE.</em></p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><p>If you have read all the series of articles I have written till now, you probably want to see how to build from scratch a true trading robot that works. I will be honest with you, this is not the holy grail of trading, you will not become a millionaire with a free idea on the internet but this could be your first step to making a profitable trading algorithm so I hope you enjoy this series of publications where we will explore how to get from a statistical idea to a functional trading robot.</p><p>So the first step is to formulate the idea and this idea came when I was teaching algorithmic trading to one of my students. We were discussing momentum strategies particularly how to measure the strength of the momentum in the market. After a long walk at a park in my city, I realized that a simple linear regression could solve the problem because it has a component that measures the direction of the market (direction of the slope) and has a measure that we can interpret as the strength (significance level of the slope). I will try to explain this a little bit more in the next lines before developing the pseudo-algorithm of this strategy.</p><p>Getting back to the idea I had about the measure of the strength of the market, I remember my university lessons on statistics that we could resume on the next figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zO-19poz5_uBMSepPzzwbQ.png" /></figure><p>Imagine you have two graphs (a and b) you can note that the direction of the market, given by the closing price of the asset, in both graphs, is upwards but the difference between these two graphs is in the distance between each of the points so in the a) graph you can notice how they are closer to each other while in graph b) they are more dispersed and thus have a direct impact on what the significance level of the regression slope and thus in the measure of the strength of the market.</p><p>First, if we got more dispersed closing prices, we can say that there is a lot of volatility and despite the average price is growing, this growth is more volatile and we will have less confidence in the future market direction. In the other case, where there is less dispersion of the closing price, we can have more confidence about the short-term direction of the market. This way of thinking leads us to the concept of the confidence level that depends on the volatility of the data points with more volatility less confidence level of the slope and with less volatility more confidence over the slope ( if you want to learn more about linear regression I strongly recommend you this video <a href="https://www.youtube.com/watch?v=7ArmBVF2dCs">https://www.youtube.com/watch?v=7ArmBVF2dCs</a> ).</p><p><strong>The Pseudo-Algorithm</strong></p><p>Until here we have the idea but we don’t have anything about the functionality of the trading robot and this is why the pseudo-code of the trading robot is an important step to build your own algorithm. The pseudo-code should contain:</p><ol><li>The opening trade conditions</li><li>The trade modification conditions</li><li>The closing trade conditions</li></ol><p>Then, after defining these conditions you will realize the other functionalities you have to develop in order to automatize the strategy for example you could realize that you will need to develop a function that compares the current market price with some predefined levels or for example, that you have to build a function that checks how many trades are opened.</p><p>Resuming the idea, the pseudo-code could be a text, a schema, or a drawing that describes the condition and functionalities of your trading algorithm.</p><p><strong>The Linear Regression Pseudo-Code</strong></p><p>The best way to make a pseudo-code is to graph it like a flow process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*QLvSue3hH76vzQjAQQu_Pg.png" /></figure><p>Here we have the pseudo-code of the linear regression robot. Note that the first step is to get the symbol data (see my previous article How to get the market info <a href="https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-introduction-ii-the-basics-45e7ae3991e2">https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-introduction-ii-the-basics-45e7ae3991e2</a>). Then, we have to make the linear regression to obtain the coefficient and its significance level (value) (we will see how to do that in the next part of this series). Next, having these two values calculated, we will make the decision like this:</p><ul><li>If we have a positive coefficient and it is significative at a certain value, we will see later how to determine that value, we buy because there is a “strong” bullish momentum</li><li>If we have a negative coefficient and it is significative at a certain value we sell because there is a “strong” bearish momentum</li></ul><p>If you have already read my previous stories, you will know how to send market execution orders, if you don’t know yet I invite you to read this post (<a href="https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-creating-a-very-simple-martingale-system-cff848ccf9e5">https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-creating-a-very-simple-martingale-system-cff848ccf9e5</a>). The last element of the strategy is the exit condition but, in order to keep it simple, we will just send each trade with an Stop Loss and a Take profit.</p><p>We have now the elements to start coding this strategy. We will do this in the next post! Hope you have enjoyed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c343e74758d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Closing all Trades at Once]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-closing-all-trades-at-once-e7398065f091?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7398065f091</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[trading-robot]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 18:55:44 GMT</pubDate>
            <atom:updated>2023-06-20T18:58:34.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZrH98vcpLPIYz2b2NwhQg.jpeg" /></figure><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><p>One common functionality that any trading robot must have is to close the trades you have opened. In this short article, we will learn how to do this in Python3 and Metatrader 5.</p><p>First, we need to review that on MT5 integration with Python there is a function called positions_get() that returns a pandas dataframe with the information of all opened orders with the next structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*j_Imuvv-VvaKYniSXXM2vQ.png" /></figure><ul><li>time : A column that indicates the time when the trade was opened</li><li>time_msc: A column that indicates the time when the trade was opened in milliseconds</li><li>time_update: A column that indicates the updated time (when we get the dataframe)</li><li>time_update_msc: A column that indicates the updated time (when we get the dataframe) in milliseconds</li><li>type: type of the trade that takes the value of 0 when is a long (buy) and 1 when is a short (sell)</li><li>magic: magic number of the trade (it is just an identifier for the strategy)</li><li>identifier: trade number</li><li>reason: MQL reason identifier</li><li>volume: volume of the trade</li><li>price_open: open price of the trade</li><li>sl: stop loss of the trade,</li><li>tp: take profit of the trade</li><li>price_current: current price of the trade</li><li>swap: accumulated swap of the tarde</li><li>profit: current profit of the trade</li><li>symbol: symbol of the open trade</li><li>comment: comment of the trade</li></ul><p>Now that we know what the dataframe looks like we could start building the function to close all trades at once! we will start by defining the function with just one argument that will be the dataframe oftained using positions_get() and making a new one and after that get the unique tickets of the opened trades:</p><pre>def close_all_open_operations(self,data:pd.DataFrame) -&gt; None:<br>      <br>        df_open_positions = data.copy()<br>        list_ops = df_open_positions[&#39;ticket&#39;].unique().tolist()</pre><p>After this, we are going to iterate over the list of trades closing one by one using a for loop. This for will take the trades’ information specially the symbol, the type, and the volume.</p><pre>def close_all_open_operations(self,data:pd.DataFrame) -&gt; None:<br>        <br>        df_open_positions = data.copy()<br>        list_ops = df_open_positions[&#39;ticket&#39;].unique().tolist()<br><br>        for ops in list_ops:<br>            df_op = df_open_positions[df_open_positions[&#39;ticket&#39;] == ops]<br>            price_close = df_operacion[&#39;price_current&#39;]<br>            tipo_operacion = df_op[&#39;type&#39;].item()<br>            simbolo_operacion = df_op[&#39;symbol&#39;].item()<br>            volumen_operacion = df_op[&#39;volume&#39;].item()</pre><p>This is because if we want to close a long we will have to sell the exact volume of the long position and if we want to close a short position we should buy the exact volume. Taking into account this, we will send a buy if the trade type is 1 and a sell if the trade type is 0. This logic in code looks like this:</p><pre>def close_all_open_operations(self,data:pd.DataFrame) -&gt; None:<br>        <br>        df_open_positions = data.copy()<br>        list_ops = df_open_positions[&#39;ticket&#39;].unique().tolist()<br><br>        for ops in list_ops:<br>            df_op = df_open_positions[df_open_positions[&#39;ticket&#39;] == ops]<br>            price_close = df_op[&#39;price_current&#39;]<br>            type_op = df_op[&#39;type&#39;].item()<br>            simb_op = df_op[&#39;symbol&#39;].item()<br>            volume_op = df_op[&#39;volume&#39;].item()<br><br>            if type_op == 1:<br>               tip_op = mt5.ORDER_TYPE_BUY<br>               close_request = {<br>                    &#39;action&#39;: mt5.TRADE_ACTION_DEAL,<br>                    &#39;symbol&#39;:simb_op,<br>                    &#39;volume&#39;:volume_op,<br>                    &#39;type&#39;: tip_op,<br>                    &#39;position&#39;: ops,<br>                    &#39;comment&#39;:&#39;Cerrar posiciones&#39;,<br>                    &#39;type_filling&#39;: mt5.ORDER_FILLING_FOK<br>                                }<br>               mt5.order_send(close_request)<br>            if type_op == 0:<br>                tip_op = mt5.ORDER_TYPE_SELL<br>                close_request = {<br>                    &#39;action&#39;: mt5.TRADE_ACTION_DEAL,<br>                    &#39;symbol&#39;:simb_op,<br>                    &#39;volume&#39;:volume_op,<br>                    &#39;type&#39;: tip_op,<br>                    &#39;position&#39;: ops,<br>                    &#39;comment&#39;:&#39;Cerrar posiciones&#39;,<br>                    &#39;type_filling&#39;: mt5.ORDER_FILLING_FOK<br>                                }<br>                mt5.order_send(close_request)<br><br></pre><p>Hope this function will help you in your trading Robot!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7398065f091" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Building an Intraday Strategy with Pivot Points]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-building-an-intraday-strategy-with-pivot-points-d6423c54480f?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6423c54480f</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[mt5-platform]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Wed, 03 May 2023 02:52:01 GMT</pubDate>
            <atom:updated>2023-06-19T22:04:40.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFrElRTAquXR_U_aBP1mdA.jpeg" /></figure><p><em>Today I am going to share with you a simple strategy that uses pivot points in order to send pending orders. If you want to know the basics of pending orders i recommend you this post:</em></p><p><a href="https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-working-with-pending-orders-c9ac3f5074ea">https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-working-with-pending-orders-c9ac3f5074ea</a></p><p><em>Disclaimer: Trading, even automated, is a risky activity. The use of this code could lead you to money losses. Use it under your own responsibility!</em></p><p>Intraday Strategies are a pull of trading strategies in which positions are opened and closed within the same trading day. These strategies seek to identify short-term market trends and make quick decisions to maximize profits. With this definition made, we can introduce the pivot points that use the OHLC (Open, High, Low, Close) data structure to define the resistance and support levels of the current day using the previous day&#39;s information.</p><p>According to the last I mentioned, the pivot points strategy states that the price of the next session will be bearish if it is under the support level, that will be bullish if the price is above the resistance levels, and that will have no tendency if the prices are between the support and resistance level. Due this Pivot point strategy is, at the same time, a Mean Reversion Strategy and a Momentum Strategy because we can trade de breakthrough of the support or resistance or the reversion when these prices are reached.</p><p>With this definition the strategy with pivots points will be the next: First I will identify the daily candle of an asset we desire in order to extract the OHLC prices to calculate the support and resistance levels according to the next formulas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*rz04OnfpLJCOjEb6Im1SPw.png" /></figure><p>With the support and resistance calculated, we will send two pending orders: One to trade the possibility of mean reversion and the other to trade the breakthrough but let’s build it step by step:</p><p>First, we will import the libraries and define a function to get the price data with three parameters: the symbol, the timeframe, and the number of candles that we want:</p><pre>import pandas as pd<br>import numpy as np<br>import MetaTrader5 as mt5<br>import  datetime<br>import pytz <br><br>#Function to extract the data<br><br>def extract_data(symbol,num_candles,time_frame):<br>    rates = mt5.copy_rates_from_pos(symbol,time_frame,0,num_candles)<br>    rates_frame = pd.DataFrame(rates)<br>    rates_frame[&#39;time&#39;] = pd.to_datetime(rates_frame[&#39;time&#39;], unit = &#39;s&#39;)<br><br>    return rates_frame</pre><p>Then we will define a function to calculate the pivot points:</p><pre>def calculate_pivot_points(df):<br>  <br>#df is a dataframe with the last candle. We use max, min to be sure that we are taking the max or the min<br>  last_24 = df.copy()<br>  # Here we calculate the pivot point<br>  pivot = (last_24[&#39;high&#39;].max() + last_24[&#39;low&#39;].min() + last_24[&#39;close&#39;].iloc[-1])/3<br>  <br># Then we calculate the support and resistance levels<br>  f_support = pivot*2 - last_24[&#39;high&#39;].max()<br>  s_support = pivot - (last_24[&#39;high&#39;].max() - last_24[&#39;low&#39;].min())<br>  t_support = last_24[&#39;low&#39;].min() - 2*(last_24[&#39;high&#39;].max() - pivot)<br>  f_resistance = pivot*2 - last_24[&#39;low&#39;].min()<br>  s_resistance = pivot + (last_24[&#39;high&#39;].max() - last_24[&#39;low&#39;].min())<br>  t_resistance = last_24[&#39;high&#39;].max() + 2*(pivot - last_24[&#39;low&#39;].max())<br><br>  return f_support, s_support, t_support, f_resistance, s_resistance, t_resistance<br></pre><p>After defining these two functions, we will use them to get the pivot points and send the pending order to trade the mean reversion. Note that if we intend to trade a mean reversion, we will send a limit operation with a stop loss to the second support/resistance that will be the level to trade the breakthrough strategy.</p><p>Let’s see the code!</p><pre>symbol = &#39;EURUSD&#39;<br><br># We get the last daily candle. Note that i take the first record of the table<br># the last record is the current daily candle.<br><br>df_lastdays = extract_data(symbol,2,mt5.TIMEFRAME_D1)<br><br>df_last = df_lastdays.head(1)<br><br>f_support, s_support, t_support, f_resistance, s_resistance, t_resistance = calculate_pivot_points(df_last)<br><br># Trade the Mean reversion<br><br>pending_buy= {<br>        &quot;action&quot;: mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;: symbol,<br>        &quot;volume&quot; : 0.05,<br>        &quot;price&quot;: f_support,<br>        &quot;sl&quot;: s_support,<br>        &quot;type&quot; : mt5.ORDER_TYPE_BUY_LIMIT,<br>        &quot;magic&quot;: 202304,<br>        &quot;comment&quot;: &#39;MR&#39;,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC<br>    }<br><br>mt5.order_send(pending_buy)<br><br>pending_buy= {<br>        &quot;action&quot;: mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;: symbol,<br>        &quot;volume&quot; : 0.05,<br>        &quot;price&quot;: f_resistance,<br>        &quot;sl&quot;: s_resistance,<br>        &quot;type&quot; : mt5.ORDER_TYPE_SELL_LIMIT,<br>        &quot;magic&quot;: 202304,<br>        &quot;comment&quot;: &#39;MR&#39;,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC<br>    }<br><br>mt5.order_send(pending_buy)<br><br></pre><p>Then we will send the orders to trade the Breakthrough:</p><pre><br># Trade the Breakthrough<br><br>pending_buy_stop = {<br>        &quot;action&quot;: mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;: symbol,<br>        &quot;volume&quot; : 0.05,<br>        &quot;price&quot;: s_support,<br>        &quot;sl&quot;: t_support,<br>        &quot;type&quot; : mt5.ORDER_TYPE_BUY_STOP,<br>        &quot;magic&quot;: 202304,<br>        &quot;comment&quot;: &#39;MR&#39;,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC<br>    }<br><br>mt5.order_send(pending_buy_stop)<br><br>pending_sell_stop = {<br>        &quot;action&quot;: mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;: symbol,<br>        &quot;volume&quot; : 0.05,<br>        &quot;price&quot;: s_resistance,<br>        &quot;sl&quot;: t_resistance,<br>        &quot;type&quot; : mt5.ORDER_TYPE_SELL_STOP,<br>        &quot;magic&quot;: 202304,<br>        &quot;comment&quot;: &#39;MR&#39;,<br>        &quot;type_filling&quot;: mt5.ORDER_FILLING_IOC<br>    }<br><br>mt5.order_send(pending_sell_stop)<br></pre><p>Hope you’ve enjoyed the code!!!</p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6423c54480f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Get the Open Trades]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-get-the-open-trades-f5778bd46423?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5778bd46423</guid>
            <category><![CDATA[metatrader]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 14:14:53 GMT</pubDate>
            <atom:updated>2023-06-19T22:05:37.049Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most used features in algorithmic trading is to modify or close open trades. But before doing this, we should identify first the opened trades that we have and also know the structure of the data that we get in order to deal with it.</p><p>For this purpose, we will use the mt5 method <em>positions_get()</em>. This method retrieves a list with two lists inside, one with the names of the properties and the other with the information. So in order to get a beautiful <em>dataframe</em> that we can handle we will transform the output of <em>positions_get()</em> using the next line of code:</p><pre>import pandas as pd<br>import MetaTrader5 as mt5<br><br>o_pos = mt5.positions_get()<br>df_pos = pd.DataFrame (list(o_pos), columns=o_pos[0]._asdict().keys())</pre><p>At first, you may think that this code is too simple but there is a catch: If there are no positions opened the 4th line of code will generate an error because o_pos will be an empty object. To handle this possible error, we will incorporate these two lines of code into a try-except statement and we will create a function in order to not repeat the code if we must do the same in several parts of the code.</p><pre>import pandas as pd<br>import MetaTrader5 as mt5<br><br>def get_all_positions():<br>        <br>        try:<br>            #mt5.initialize( login = name, server = serv, password = key, path = path)<br>            o_pos = mt5.positions_get()<br>            df_pos = pd.DataFrame (list(o_pos), columns=o_pos[0]._asdict().keys())<br>            print(&quot;There is at least one open trade&quot;)<br>                <br>        except :<br>            df_pos = pd.DataFrame()<br>            print(&quot;There are not opened trades&quot;)</pre><p>Now that we can get the open trades, we must understand what information we get when we use this function.</p><h4>The Data that We Get</h4><p>So far we have learned about how to get open trades. Now the question is what kind of information do we get?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYae_bHLxtFU_f1A_mFF9A.png" /></figure><p>The <em>dataframe</em> that we get from the function above, retrieves us a lot of fields but the most important are:</p><ul><li>Ticket</li><li>Time ( Time when we open the position)</li><li>Time_sc (Current time)</li><li>Time_update (Time when we</li><li>type (type of trade operation, 1 if short 0 if it is long)</li><li>Magic (custom id of the operation)</li><li>Volume</li><li>Price_open (open price)</li><li>SL and tp (stop loss and take profit)</li><li>Price_current (current price)</li><li>swap</li><li>profit (profit of the trade operation)</li><li>symbol</li><li>comment (comment on the trade operation)</li></ul><p>With this information, we could do a lot of other trade functionalities like a break-even function, a trailing stop, and a lot more that we will build in the next posts.</p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5778bd46423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Working with Pending Orders]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-working-with-pending-orders-c9ac3f5074ea?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ac3f5074ea</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-bot]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 23:41:07 GMT</pubDate>
            <atom:updated>2023-06-19T22:06:18.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJ2sWWMRb-vzCgzXd5dKRg.png" /></figure><p>A lot of trading strategies don’t require instant execution by the market. Sometimes buy or sell an asset requires calculate a price level and then put the pending orther in the market .</p><p>For example, imagine a simple trading strategy that calculates the maximum and minimum of an asset of the last three trading days and then put buy signal on the minimum and sell signal on the maximum.</p><p>To do that we sould first get the last trhee day information of the asset. If you have read my previous post you should be able to do this easily. If you don’t here is the code.</p><pre>Import pandas as pd<br>Import numpy as np<br>Import Metatrader5 as mt5<br><br>nombre = 187652387<br>clave = &quot;mypassword&quot;<br>path = r&#39;C:\Program Files\MetaTrader 5\terminal64.exe&#39;<br><br>mt5.initialize(login = nombre, password = clave, server = servidor, path = path)<br>rates = mt5.copy_rates_from_pos(&#39;EURUSD&#39;, mt5.TIMEFRAME_M5, 0, 864)  <br>rates_frame = pd.DataFrame(rates)<br>rates_frame[&#39;time&#39;]=pd.to_datetime(rates_frame[&#39;time&#39;], unit=&#39;s&#39;)<br><br></pre><p>After get the data, we will then calculate the maximum and the minimum price of the last 864 five minutes candles (or last 3 day information) to calculate these two values.</p><pre>max_value = rates_frame[&#39;high&#39;].max() #The highest value reached by the price<br>min_value = rates_frame[&#39;low&#39;].min() #The minimum value reached by the prices</pre><p>With theese to values calculated, we can then send the pending orders. To do this, we will use the basic structure of an operation ( <a href="https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-the-only-mql-you-need-to-know-c9f15353fb4d">Read this post for more details</a>) and will modify a little bit. First we will change the “action” element of the dictionary for <em>mt5.TRADE_ACTION_PENDING, </em>then we will change the type element with the with the desired operation. But before to show the code remember this graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*Wovaj59tZJ699BQWGWdjNg.png" /><figcaption>Taken from someone on the internet</figcaption></figure><p>After recall the types of pending orders we can translate them into Python:</p><ul><li>buy limit= mt5.ORDER_TYPE_BUY_LIMIT</li><li>sell limit= mt5.ORDER_TYPE_SELL_LIMIT</li><li>buy stop = mt5.ORDER_TYPE_BUY_STOP</li><li>sell stop = mt5.ORDER_TYPE_SELL_STOP</li></ul><p>With this small traduction, we can define a little mean reversion strategy (i will talk about this kind of strategy on future posts) that follows the rule we talk at the begining of the post.</p><pre>request = {<br>        &quot;action&quot;:mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;:&#39;EURUSD&#39;,<br>        &quot;type&quot; : mt5.ORDER_TYPE_BUY_LIMIT,<br>        &quot;price&quot;: min_value,<br>        &quot;volume&quot;:1.0,<br>        &quot;comment&quot;:&#39;Test_code&#39;,<br>        &quot;type_filling&quot;:mt5.ORDER_FILLING_IOC<br>}<br><br>mt5.order_send(request)<br><br>request = {<br>        &quot;action&quot;:mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;:&#39;EURUSD&#39;,<br>        &quot;type&quot; : mt5.ORDER_TYPE_SELL_LIMIT,<br>        &quot;price&quot;: max_value,<br>        &quot;volume&quot;:1.0,<br>        &quot;comment&quot;:&#39;Test_code&#39;,<br>        &quot;type_filling&quot;:mt5.ORDER_FILLING_IOC<br>}<br><br>mt5.order_send(request)</pre><p>Note that we replace the “price” element of the dictionary together with the min value, to create the buy pending order, and with the max value to create the the sell pending orther.</p><p>The full code:</p><pre>Import pandas as pd<br>Import numpy as np<br>Import Metatrader5 as mt5<br><br>nombre = 187652387<br>clave = &quot;mypassword&quot;<br>path = r&#39;C:\Program Files\MetaTrader 5\terminal64.exe&#39;<br><br>mt5.initialize(login = nombre, password = clave, server = servidor, path = path)<br>rates = mt5.copy_rates_from_pos(&#39;EURUSD&#39;, mt5.TIMEFRAME_M5, 0, 864)  <br>rates_frame = pd.DataFrame(rates)<br>rates_frame[&#39;time&#39;]=pd.to_datetime(rates_frame[&#39;time&#39;], unit=&#39;s&#39;)<br><br>request = {<br>        &quot;action&quot;:mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;:&#39;EURUSD&#39;,<br>        &quot;type&quot; : mt5.ORDER_TYPE_BUY_LIMIT,<br>        &quot;price&quot;: min_value,<br>        &quot;volume&quot;:1.0,<br>        &quot;comment&quot;:&#39;Test_code&#39;,<br>        &quot;type_filling&quot;:mt5.ORDER_FILLING_IOC<br>}<br><br>mt5.order_send(request)<br><br>request = {<br>        &quot;action&quot;:mt5.TRADE_ACTION_PENDING,<br>        &quot;symbol&quot;:&#39;EURUSD&#39;,<br>        &quot;type&quot; : mt5.ORDER_TYPE_SELL_LIMIT,<br>        &quot;price&quot;: max_value,<br>        &quot;volume&quot;:1.0,<br>        &quot;comment&quot;:&#39;Test_code&#39;,<br>        &quot;type_filling&quot;:mt5.ORDER_FILLING_IOC<br>}<br><br>mt5.order_send(request)</pre><p>We have a lot to discuss about pending orders. But for now you can practice and adapt this simple code to your strategy!</p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ac3f5074ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Arbitrage: A key Concept for Algorithmic Trading]]></title>
            <link>https://medium.com/@elospieconomics/statistical-arbitrage-a-key-concept-for-algorithmic-trading-cf8d6a4fd8e3?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf8d6a4fd8e3</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 02:02:23 GMT</pubDate>
            <atom:updated>2023-06-19T22:06:59.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*QDKxrHyXmEKtm4PeL_u7Lg.png" /></figure><p>Algorithmic trading is a term hard to define. There is no concrete definition for the term. If you make a quick search on google you will find something like this:</p><p><em>“Algorithmic trading is an automatic process that inserts or pulls out money into or out of the market”</em></p><p>The definition above is very general and any algorithm, or script of code, that buys or sells any active can fit into this definition and it really doesn’t say anything about the true job of an algorithmic trader (developer). Also, that definition doesn’t differentiate between two ways to do trading: <em>“Technical”</em> trading and Statistical trading. The first way of trade, and this could be controversial, relies on a visual analysis of the market and it is not technical at all because if it were “technical” everybody will see the same information from the chart, that type of analysis has no clear technique, is simply not objective. The second way to trade is with statistics by finding probabilities, possible price paths with some degree of certainty. Furthermore, when you do statistical trading, you use robust statistical and/or mathematical techniques that allow you to be objective and confident with your decisions. I have never seen a chartist trader being 99% confident at the time to draw a tendency line or at least saying “my probability of winning this trade is 76%” for instance.</p><p>These differences between statistical trading and <em>“technical”</em> trading lead us to the term of this post: <strong>statistical arbitrage. Statistical arbitrage </strong>could be defined as a trade that is made based on the statistical properties of the market with the objective to make a profit from it. But not any kind of profit is a singular profit called <strong>alpha</strong>. This last term refers to a profit that is above the simple strategy of buying and holding the asset that is traded.</p><p>At this point, we can create a new concept of algorithmic trading, more robust and really more technical:</p><p><em>“Algorithmic trading is an automatic process that makes statistical arbitrage in the market”</em></p><p>With this new definition, and more concrete, we can have a more detailed perspective of the job that an algorithmic trader (or developer) does: Find statistical properties of the asset, find, with a method, the best and safest way to make money from the market.</p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf8d6a4fd8e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading with Python and MT5: Creating a very simple Martingale system]]></title>
            <link>https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-creating-a-very-simple-martingale-system-cff848ccf9e5?source=rss-c591bb4560cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff848ccf9e5</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[martingale-strategy]]></category>
            <category><![CDATA[metatrader-5]]></category>
            <dc:creator><![CDATA[Sebastian Ospina Valencia]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 00:20:22 GMT</pubDate>
            <atom:updated>2023-06-19T22:11:00.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aj_1reW_q-K1RYVfiGFNjQ.jpeg" /></figure><p>One of the most used, and dangerous, trading techniques is the Martingale. It consists, in few words, in play against the market. If the market is downwards you will open longs hoping that the market will correct upwards while if market is upwards, it will open shorts hoping the market to correct downward. The catch is that if the the market makes a very strong sell-off, for example, your martingale strategy could evaporate your account in few seconds. Leaving this concern behind, today we will show how to develope this simple strategy using Python and MT5.</p><p><strong><em>Disclaimer:</em></strong><em> the code presented here is </em><strong><em>JUST FOR EDUCATIONAL PURPOSES</em></strong><em>. Any use for real investment is not responsibility of the author. Use it under your own responsibility. Trading, even the automated,is a risky way to make money</em></p><p><strong>The sketch of the algorithm:</strong></p><p>First we will build a Pseudo algorithm that describes our simple trading strategy. First some conditions:</p><ol><li>If the last variation was positive, we will open a long position with certain TP</li><li>Then, for each new buy order, that we open, we will open a short position with the same TP range but this time the volume will be 2 times the original volume.</li></ol><p>3. We will not use the stop loss (Warning: this is very risky)</p><p>With this conditions we need to have, beside the symbol data:</p><ol><li>Current operations</li><li>last price variation</li></ol><p>For the current number of open positions we will use the mt5 function positions_get() and we will incorporate this function within a try except to create a variable called var.</p><p>This variable we will use it to set the number of times we will increase the operation volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Y8QlV3eAb1yAnssSY2WoNw.png" /></figure><p>Also we will define a variable called range1 that will be used to compute the TP price for the operations</p><p><em>range1 = 10</em></p><p>Then we will define that everytime we run the code open a long position if the last variation was positive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*qnsraH8kwvE02h47kZAYQw.png" /></figure><p>After that, then we will tell our algorithm to open another long position if there is no operation and the last price’s variation was positive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*UdMk85mjnzTGgtCjs6tlug.png" /></figure><p>Lastly, we will implement the martingale system: If there is at least one long operation, then open a short position with var times the initial volume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*hV3QVY_5ivsJrFfmii5jpA.png" /></figure><p>And so we have one simply and risky simple martingale robot. You could find the full implementation on:</p><p><a href="https://gitlab.com/elospieconomics/algorithmic-trading">https://gitlab.com/elospieconomics/algorithmic-trading</a></p><p><em>Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff848ccf9e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>