Step-by-step instructions for 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 do not understand this, I am special. the terminology is unknown. And it’s not clear how to start. ” This is what we will work on! 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 market game;
  • Brokers;
  • API for trading / Example of a robot;
  • Deployment online;
  • Final thoughts.


The essence of the stock market game


There are many theories and explanations. But we will approach the issue from the point of view of the software engineer and the concept of levels of abstraction. The essence of the game is very simple (but true): there is a graph of some (pseudo?) Random variable (price). Her story is known for a rather large period. The task is to predict the movement (up or down). All. Really. What traders do is predict whether the price will go up or down and bid on them (open trades): buy (buy / long) some amount of “product” (instrument) in the hope of going up, or sell (sell / short) in the hope that it will go down.
After some time (if the price has changed significantly) open trades are closed and they receive a profit (guessed with the move) or a loss (did not guess).

You can close the deal by hand, or you can automatically (order): you can declare it in advance - if the price reaches a certain level, then close the trade.

Access to the market for transactions provides a broker. And for this he charges a fee for each transaction.

Grounded in theory, we can again return to an area far from finance and say: hey! Yes, we are just looking for a signal in the noise! Now we will quickly expand the Fourier series, determine the frequencies, and get rich!

That's right, that's all. The game started.

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:

  • Reputation;
  • The opportunity to open a deal at 1 dollar and there are no requirements for the size of trade (some brokers oblige to make it a multiple of large values);
  • Low transaction price (narrow spread);
  • A huge number of instruments: currencies, precious metals and oil, indices;
  • Ability to trade through the API;
  • Input money withdrawal is possible through PayPal.


In order to trade, you need to create an account on Oanda. To begin with - training (fxtrade practice). In the menu "Manage API Access" you need to indicate that trading through the API is possible on your account. After that, a secret token will be generated 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:

Get pricing information. The robot must know what is happening.

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 flow of 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 about the name of the instrument, price and time are transferred to the function of the strategy.
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, anything.

Let's say the robot thought and said: as if the price would go up! I feel my shiny metal ass!

Then we need an 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) 


That, in general, is all. We learned how to get price information and, based on this, open deals with fixed goals.

Deployment online


I discovered the availability of vps at bargain prices. For example, ftpit.com. He took one for 2 dollars a month.
This host has no problem keeping 3 of my robots, which day and night are trying to defeat the moneybags from Wall Street. Plus, it has its own SMTP server and a small site.

Final thoughts


Trading in financial markets can be a wonderful hobby, which not only makes it possible to program, but also join a huge online game, in which every day 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 staying on a practice account for at least 1 year,
do not rush to enter real money
if you see that you have direct money and everything works, then simply monitor the account here - forexfactory.com
if there is a stable result even on a demo account - investors themselves will seek you and offer money for management

UPDATE 2


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

Also popular now: