Good day to all!
My name is Ilya and today I want to tell you a little about my hobby - cryptocurrency algo-trading. Soon there will be a year, as I was overtaken by the idea of writing a trading robot that would minimize the human factor of trade (trading people probably know what is to update the balance every five minutes and often make some hasty, and therefore incorrect, trading decisions). Therefore, it was decided to shift everything to the robot, remove the application for viewing courses from the phone and begin to sleep peacefully. Having spent a lot of time writing something more or less working, I want to give the reader a small overview, where to start in this fun (and nervous) field, like algorithmic trading. This guide is not a call to start trading, it does not contain investment advice, only educational objectives are pursued.
As you can see from the title, the robot that we will write will work on the BitMEX exchange. The choice is explained very simply - there are shoulders up to 100. And our robot will work with margin.
For those who do not understand what I'm talking about. Margin trading is trading with leverage. [1] What is leverage?
Leverage is the ratio of your deposit to the lot you work with. Those. having a deposit of $ 100, you can make a deal with a lot of 10,000, and then it will be 1 to 100. If you set the lot to 5,000, then the leverage will be 1 to 50, etc. [2]
So, I hope that the reader has a basic knowledge of trading on the stock exchange, for example, what is OHLCV candles (aka candlesticks), that there are different time intervals for their presentation, etc.
Well, let's get down to our little adventure in the country of algorithmic margin trading?
I’m a fan of top-down communication and therefore I’ll start by telling you what I’m going to do, and then we’ll start implementing. Globally, there are two important things that need to be done to launch a robot: develop a decision-making strategy (under what conditions to buy) and develop logic on top of the decision made (how much and how to buy).
The decision-making strategy (brain) in our case will consist of the MACD indicator (Eng. Moving Average Convergence / Divergence) - convergence / divergence of moving averages). The indicator is used to check the strength and direction of the trend, as well as determine pivot points. Based on moving averages. There are two modifications of the MACD indicator: linear MACD and MACD-histogram. [3] We will use the implementation of the MACD-histogram from the TA-lib library and based on this indicator we will make a decision on the purchase or sale.
The logic over the solution of our indicator will be simple: if the indicator says to buy, then we will buy, if we sell, we will sell. We will trade a fixed amount of money with a fixed leverage.
The first thing we start with is installing the necessary libraries. First we need an exchange client, we take it here . The brain of our robot will be based on technical analysis, so you need to put the library TA-lib. Well, the standard set - numpy, pandas.
After installing all the necessary libraries, I suggest the reader to register at https://testnet.bitmex.com - this is a copy of the BitMEX exchange, but there you trade not with real money, but with virtual money. It is very convenient to use for debugging robots before launching on a real exchange. After registration, we create our own keys and create an exchange client:
client = bitmex.bitmex( test=True, api_key="YOUR_KEY", api_secret="YOUR_SECRET" )
Pay attention to the test parameter. It is set to true, which means that we will trade on a test exchange. This post will not be about using the API of the exchange, you can redirect all arising questions on it to the API explorer , since it is very convenient for them.
The next step is to get the data for use on the MACD indicator. We get 100 candles with a resolution of 1 hour.
ohlcv_candles = pd.DataFrame(client.Trade.Trade_getBucketed( binSize=self.timeframe, symbol='XBTUSD', count=100, reverse=True ).result()[0])
Now we have a data frame with candles, let's apply the indicator.
macd, signal, hist = talib.MACD(ohlcv_candles.close.values, fastperiod = 8, slowperiod = 28, signalperiod = 9)
I chose these parameters after playing a little with the strategy and its backtest on the Trading View. Here are examples of pictures with entry / exit points of the strategy on the chart and how much money it earned. But remember, this strategy was tested without leverage.
So, having received the indicator, let's understand how to make a decision based on it. Well, everything is simple. When the histogram crosses the zero value from bottom to top, this is a signal to buy, and vice versa.
#sell if hist[-2] > 0 and hist[-1] < 0: return -1 #buy if hist[-2] < 0 and hist[-1] > 0: return 1 #do nothing else: return 0
Everything is very simple and clear. Let's make it into one class, which we call strategy.
class Strategy(): def __init__(self, client, timeframe='5m'): self.client = client self.timeframe = timeframe def predict(self): ohlcv_candles = pd.DataFrame(self.client.Trade.Trade_getBucketed( binSize=self.timeframe, symbol='XBTUSD', count=100, reverse=True ).result()[0]) macd, signal, hist = talib.MACD(ohlcv_candles.close.values, fastperiod = 8, slowperiod = 28, signalperiod = 9) #sell if hist[-2] > 0 and hist[-1] < 0: return -1 #buy if hist[-2] < 0 and hist[-1] > 0: return 1 #do nothing else: return 0
Now let's write the performer of our decisions. The logic is simple - the strategy told us to buy, so we buy. I will give the merchant code immediately, there is nothing complicated in it:
class Trader(): def __init__(self, client, strategy, money_to_trade=100, leverage=5): self.client = client self.strategy = strategy self.money_to_trade = money_to_trade self.leverage = leverage def execute_trade(self): prediction = self.strategy.predict() print(f"Last prediction: {prediction}") try: if prediction == -1: response = self.client.Order.Order_new( symbol="XBTUSD", side="Sell", orderQty=self.money_to_trade * self.leverage, ).result() if prediction == 1: response = self.client.Order.Order_new( symbol="XBTUSD", side="Buy", orderQty=self.money_to_trade * self.leverage, ).result() except Exception as e: print("Something goes wrong!") print(str(e)) return
A small nuance - to simplify your life, orders are executed here not at the price set in advance, but at the market price. In the case of BitMEX, this is good for two reasons:
Now we have the logic of decision-making, we have the logic of execution of decisions, it remains to put this whole thing together. We need to start the process of trading once a selected time period, in this case it was 1 hour. I will do it with a crutch in the name of the speed of writing, but it is better to do it, for example, through cron.
time_to_wait_new_trade = 60*60 #sec strategy = Strategy(client, timeframe='1h') trader = Trader(client, strategy) while True: if round(time.time()) % time_to_wait_new_trade == 0: trader.execute_trade() time.sleep(10)
Well, now this business can be arranged in one script and boldly run, but only on the test exchange! I do not advise you to do this on a real exchange, because you can lose money. The purpose of this script was to show that it was easy to start, and you made a smarter brain for this model, you can easily earn some sums.
Jupyter notebook with the code I put in my repository , if someone is interested to view - you are welcome!
Source: https://habr.com/ru/post/358398/
All Articles