📜 ⬆️ ⬇️

Step-by-step guide to creating a trading robot in Python

The topic of online trading (whether it is forex, stocks, minerals) is usually of interest. But at the same time, many people think: “I don’t understand this, specials for me. terminology unknown. And it is not clear how to start. ” Here we will work on it! By the end of the article you will have enough knowledge and examples to start playing in the financial markets.

We cover the following points:


The essence of the stock game


There are many theories and explanations. But we come to the question from the point of view of the software and the concept of levels of abstraction. It is very simple (but true at the same time) the essence of the game is as follows: there is a graph of some (pseudo?) Random variable (price). Her story is known for quite a long period. The task is to predict the movement (up or down). Everything. Realistically. What traders do is predict whether the price will go up or down and bet on it (open trades): buy (buy / long) a certain amount of "product" (instrument) in the hope of going up, or sell (sell / short) in the hope that will go down.
After some time (if the price has changed significantly), open trades close and receive as a result to arrive (guess with a move) or loss (did not guess).

The deal can be closed with your hands, and you can automatically (order): you can declare in advance - if the price reaches such a level, then close the trade.
')
Access to the market for transactions is provided by a broker. And for this he charges for each transaction.

Being grounded by the theory, we can again return to the region far from finance and say: hey! we are just looking for a signal in the noise! Now we will quickly decompose the Fourier series, determine the frequencies and get rich!

That's right, so it is. The game has begun.

Brokers


There are many brokers who specialize in private individuals. They are distinguished by a set of tools available for bidding, service prices, reliability, the ability to create robots.

I will not give a comparative analysis. Immediately give the best - Oanda. Why Oanda:



In order to trade, you need to create an account on Oanda. To begin with - training (fxtrade practice). In the “Manage API Access” menu, you need to indicate that trading via the API is possible on your account. After that, you will generate a secret token for use in RESTful calls.

API for trading


image

developer.oanda.com/docs - RESTful
Examples: developer.oanda.com/docs/v1/code-samples

I will use Python 2.7 and the requests library.

In order to trade, we need:

Receive price information. The robot must know what is going on.

def connect_to_stream(): try: s = requests.Session() url = "https://stream-fxpractice.oanda.com/v1/prices" headers = {'Authorization' : 'Bearer ' + "YOUR TOKEN", #'X-Accept-Datetime-Format' : 'unix' } params = {'instruments' : "EUR_USD,AUD_JPY", 'accountId' : "YOUR ACC ID"} req = requests.Request('GET', url, headers = headers, params = params) pre = req.prepare() resp = s.send(pre, stream = True, verify = False, timeout=20) return resp except Exception as e: s.close() print "Caught exception when connecting to stream\n" + str(e) 


This feature will allow you to connect to the price stream for EUR / USD and AUD / JPY.

Now we can read them:

  try: #infinite loop on receiving events about price. on each tick Strategy function is called for line in response.iter_lines(1): if line: msg = json.loads(line) if msg.has_key("instrument") or msg.has_key("tick"): strategy(msg['tick']['instrument'], msg['tick']['time'], msg['tick']['ask']) except Exception as e: print "something gone bad " +str(e) return 


Now we need a brain. Making decisions

image

As you can see, information on the name of the instrument, price and time is transferred to the strategy function.
We can decide in the strategy function: what should we do with this new info? Ignore? Or maybe open a new deal?

Here it is useful that you are a programmer. Invent! There is a number series - you are looking for patterns, analyze, yes, whatever.

Let's say the robot thought and said: exactly the price will go up! Feel my shiny metal ass!

Then we need the opportunity to make a deal

 def order(instr, take_profit, stop_loss): try: url = "https://" + "api-fxpractice.oanda.com" + "/v1/accounts/"+"YOUR ACC"+"/orders" headers = {'Authorization' : 'Bearer ' + "YOUR TOKEN", #'X-Accept-Datetime-Format' : 'unix' "Content-Type" : "application/x-www-form-urlencoded" } params = urllib.urlencode({ "instrument" : instr, # ,     "units" : 10, #    "type" : 'market', #   ! "side" : "buy", # ,     ("sell"    ) "takeProfit" : take_profit #     ,    ,     .    "stopLoss" : stop_loss #    ,      " ?!!    .  .     " }) req =requests.post(url, data=params, headers=headers) for line in req.iter_lines(1): print "order responce: ", line except Exception as e: print "Caught exception when connecting to orders\n" + str(e) 


Here, in general, that's all. We learned to get information about the price and, on this basis, to open transactions with fixed goals.

Deployment online


Discovered the presence of vps at bargain prices. For example, ftpit.com. He took the one for $ 2 a month.
This host without any problems keeps on itself 3 of my robots, which day and night are trying to beat the fat cats from Wall Street. Plus, it has its own SMTP server and a small website.

Final thoughts


Trading in financial markets can be a wonderful hobby that not only makes it possible to program, but also to join a huge online game in which every day there is a lot of news, opinions, events, fear, greed and hope!

If you have questions, I will answer with joy and to the best of my ability.

image

UPDATE


I highly recommend to stay in the practice account for at least 1 year.
do not rush to enter real money
if you see that you are straightforward and everything turns out, then simply monitor the account right here - forexfactory.com
if there is a stable result even on a demo account - investors themselves will look for you and offer money to manage

UPDATE 2


He remembered who else loved to play in the financial markets - Sir Isaac Newton (the same :))

Source: https://habr.com/ru/post/241211/


All Articles