Algorithmic Trading with Python and MT5: Creating a very simple Martingale system
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.
Disclaimer: the code presented here is JUST FOR EDUCATIONAL PURPOSES. 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
The sketch of the algorithm:
First we will build a Pseudo algorithm that describes our simple trading strategy. First some conditions:
- If the last variation was positive, we will open a long position with certain TP
- 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.
3. We will not use the stop loss (Warning: this is very risky)
With this conditions we need to have, beside the symbol data:
- Current operations
- last price variation
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.
This variable we will use it to set the number of times we will increase the operation volume.
Also we will define a variable called range1 that will be used to compute the TP price for the operations
range1 = 10
Then we will define that everytime we run the code open a long position if the last variation was positive
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
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:
And so we have one simply and risky simple martingale robot. You could find the full implementation on:
https://gitlab.com/elospieconomics/algorithmic-trading
Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18