[TOC]
Summary
Quantitative trading, as a product of the combination of science and machines, is changing the landscape of modern financial markets. Many investors are now turning their attention to this area. How to minimize risk and achieve the best returns?
See also:
Quantified trading is a high-end atmosphere, overnight wealth. The era of artificial intelligence, accompanied by the rise of advanced technologies such as deep learning, big data, cloud computing, etc., gives it a mysterious color. It seems that as long as you use quantified trading, you can build a perfect and flawless trading strategy.
In fact, to a certain extent, quantitative trading has been mythologized. Quantification, aside from trading, is actually using computers and using statistics, mathematics, and other methods to find a set of trading signals that are expected through a scientific investment system. This signal system will tell us when we should buy and sell at what price.
The development of quantitative trading
The man who first used quantitative methods to analyze changes in data and discovered the law of market price fluctuations was neither a Dutchman who invented stocks, nor an Englishman who developed modern finance, nor an American who coexisted with finance when he founded the country, but a Frenchman.
As early as the 18th century, Jules Regnault, a French stockbroker's assistant, proposed the actuarial theory of stock price variations, and subsequently published a book on the theory of fluctuating probabilities and the philosophy of stock trading, in which he detailed his discovery of the law of market fluctuations (the "normal distribution"): the deviation of the fluctuation price is proportional to the square root of time, and finally the success of the trade is obtained by rational quantized investment decisions.
Today, in the context of the era of the Internet + Big Data + Cloud Computing + Artificial Intelligence, quantitative trading has also developed rapidly. The former global financial hub of London's Caterpillar Pier has long since become a hub for IT companies. The world's top investment banks are also training their own quantitative teams to try to get into the financial war that the winners of the model have been fighting for years.
In the domestic market, both hardware equipment and research and development capabilities are still in the early stages. However, more and more institutions and professional investors are aware of the benefits of quantitative trading and are participating in this field, especially in the process of gradual tightening of regulations and gradual improvement of market efficiency.
Characteristics of quantitative trading
Scientific verification: Consider that when you have a trading system, it can be very time-consuming to test its effectiveness with an analogue disk, and it can be very expensive to test it directly with a physical disk. But you can use the retrospective function in quantitative trading to test the trading system in a scientific way with a large amount of historical data.
Objectively accurateIn trading, our real enemy is ourselves, mindset management is easy to say but difficult to do. The human weaknesses of greed, fear, and luck are magnified in trading markets, and quantitative trading can help us overcome these weaknesses and make better decisions in trading.
Timely and efficientSubjective trading, the speed of human reflection is not faster than a computer, and human physical and energy are not able to run 24 hours, in the market where opportunities are fleeting, quantitative trading can completely replace subjective trading, search for trading opportunities, and quickly track market changes in a timely manner.
Risk managementQuantitative trading can not only extract historical patterns from historical data that may be repeated in the future, which are strategies with a higher probability of winning. It can also build a variety of different portfolios, reduce systemic risk, smooth the capital curve.
Opening of the breakout strategy
The half-hour of opening is often used to determine the day's trend. The strategy uses the half-hour after opening to determine whether the price is bullish or bearish as a criterion for determining the direction of the day's trend.
The strategy of the Dongch'an Tunnel
Figure 1 - 1 The strategy of the Dongch'an channel
The Dongqian channel strategy is known as the grandfather of intraday trading, and its rules are: buy at the highest price if the current price is higher than the previous N root K line's highest price, and sell at the lowest price if the current price is lower than the previous N root K line's lowest price.
The strategy of long-term options
Cross-term arbitrage is the most common type of arbitrage, based on the price of the same trading variety, contracts in different delivery months, if the price of both of them has a large spread, it is possible to buy and sell futures contracts in different periods at the same time, and cross-term arbitrage. Assuming that the price difference between the main contract and the sub-main contract is maintained for a long time at around -50 ~ 50. If the price difference reaches 70, we expect the price to return to 50 at some point in the future.
Summary
In this article, we will briefly explain the concepts of quantitative trading from the definition, development, characteristics and classic trading strategies.
Understanding quantitative trading is an important knock on the door to becoming a Quant. Finally, I wish you all the best in the bear market and an early realization of cognitive transformation!
The next sectionWhat is the difference between quantitative trading and traditional trading? In real-world trading, should you choose traditional trading or quantitative trading?
After-school homework
First, what is a quantitative transaction in one sentence? 2 What are the characteristics of quantitative trading?
Many people use complex strategic programming as an entry point to explore quantitative trading, unwittingly placing a layer of mystery on quantitative trading. In this section, we will try to make a simple sketch of quantitative trading in plain language, unraveling its mystery, believing that even unfounded white lies can be easily understood.
Subjective trading places more emphasis on artificial analysis and market sentiment, even when there are buy and sell signals, selective down-order trading, preferring to miss the market, and not wanting to make mistakes. Human feelings are complex, variable and unreliable, and most traders often turn to another method once a continuous loss has occurred. Strong randomness, susceptible to loss, leading to difficulty in stability of profits.
Quantify trading by understanding the transaction and developing a consistent buying and selling strategy. In trading, all trends are treated as peers, and all trades are processed systematically, and it is better to make mistakes than to miss. It also has a complete evaluation system, which determines which type of market and variety is best suited to the strategy by reviewing historical data, and combining multiple strategies and varieties to achieve profitability.
In a nutshell, subjective trading is the basis of quantitative trading, and quantitative trading is the refinement of subjective trading. Subjective trading is more like practicing martial arts, whether or not you can succeed in the end, talent accounts for the majority, there are decades of ignorance, but also some enlightenment. Quantitative trading is more like fitness, as long as you work hard, even if you do not have talent, you can train your muscles.
A successful subjective trader is, in a sense, also a quantitative trader. Because a successful subjective trader must have his or her own set of rules and methods, a trading system. Successful subjective trading must be based on trading discipline and trading rules, and the execution of trading rules is actually the quantitative part of subjective trading.
On the contrary, a successful quantitative trader must also be a good subjective trader, because the development of a quantitative trading strategy is actually the crystallization of a person's trading ideas. If one's perception and understanding of the market is wrong from the beginning, then the trading strategy developed is also difficult to profit from in the long run.
Thus, from a profitability perspective, the key factor in determining whether a trader will ultimately succeed is the trading concept, rather than whether it is subjective or quantitative trading. Quantitative trading seems to be superficial, and its profitability is essentially indistinguishable from subjective trading.
However, there is no denying that quantitative trading does have many advantages as a trading tool.
It's faster.To test a trading strategy, you need to compute a large amount of historical data, and quantify the results of a transaction in a matter of minutes. This is many times faster than subjective trading.
MoreThe following is a summary of the key points of the report: "To judge whether a strategy is good, it relies on data (e.g. Sharpe ratio, maximum retraction rate, annualized returns) rather than a self-contained stick".
More opportunities: There are thousands of trading varieties around the world, subjective trading is impossible to do simultaneously, but quantitative trading can be done in real time in the entire market, without missing any trading opportunity, increasing profitability.
Of course, it is possible, but it is difficult to make money in the long term. Whether or not to make money does not depend on quantitative trading itself, it is only a tool. Quantitative trading is just the process of programming, regulating, quantifying the idea of trading, and the process is only the executive power.
Quantitative trading is also risky, why? Because quantitative trading is about extracting laws from historical data and forming trading strategies. But financial markets are an ecosystem whose laws and human nature are an interactive dynamic process, and ultimately a human market. The laws of the market are influenced by human nature, and the greed and fear among human beings will change with the changes of the market.
From the above explanation, we can see that quantitative trading is not a unique method of trading, it is just a trading tool that helps us analyze the trading logic and perfect the trading strategy. Whether you are a value-oriented or technical person, whether you are doing stocks, bonds, commodities or options, you can actually quantify. Compared to traders who rely on personal experience to make decisions, the weapons in the hands of quantitative traders are market evidence and rationality.
Quantization is merely a way of trading, strategy is merely a vehicle for trading ideas, and procedures are executed by each transaction process. The following section will take you through the complete lifecycle of quantization trading, which will include: strategy conception, model building, feedback optimization, simulation trading, live trading, strategy monitoring, etc.
1 What is the most important difference between quantitative trading and subjective trading? What are the advantages of quantitative trading over subjective trading?
A complete quantitative trading lifecycle is not just a trading strategy itself. It consists of at least six components, including: strategy conception, model building, feedback optimization, simulation trading, live trading, strategy monitoring, etc.
First of all, to do quantitative trading, you have to go back to the trading market, to observe the prices in the market, to understand the laws of market fluctuations, and to try to deduce each trading logic and finally summarize the trading strategy. There are no shortcuts here, you may need to read classic investment books, or persist in trading, summarizing the experience in the event of failure.
For beginners in quantitative trading, the best way to start developing a trading strategy is to simulate. Build a strategy logic directly using ready-made technical analysis indicators, write buy and sell rules, and you get a simple strategy. If your trading strategy is like this: buy if the price is higher than the average price of the last 10 days, sell if the price is lower than the average price of the last 10 days.Figure 1-2 Example of trading strategy
Of course, with the accumulation of strategic experience and the formation of one's own trading style, the logical choices will become more and more diverse, and then progress to more systematic quantitative trading. It is a good thing to be a trader who thinks quantitatively, whether in the stock or futures markets, because such a person has the ability to consistently and steadily make profits in any trading market.
Secondly, you need to master a quantitative trading tool to write a trading strategy and implement your trading ideas. Common software on the market can do that. But if you want to become a high-end quantitative trader, you need to learn.
I'm going to talk about a computer language, and I'm going to recommend Python because it's an authoritative language for scientific computing. It also offers a variety of open source analytics packages, file processing, networking, databases, etc.
If your programming skills are weak, and believe this is also a weakness of most beginners, it is recommended to use a relatively simple visualization programming language or Ma, which can increase the interest in learning to quantify trades and allow you to focus on strategy, efficiently complete strategy development.
Figure 1-3 Trading strategy development page
The above strategy code, a Mac language demonstration using the inventor's quantification tools, integrates many functional modules that can be used directly, and supports backtesting and real-time trading capabilities, which is a good quick introduction.
Then, when the strategy model is written, the next step is to retest the strategy, as well as filter and optimize the parameters. The strategy can be retested using different parameters, observing the strategy's sharp ratio, maximum retraction, annualized returns, etc.
For example, we use historical data from 2017 as in-sample data, and historical data from 2018 as out-sample data.
Data retesting. In general, out-of-sample retesting results are good without in-sample retesting results, but if out-of-sample and in-sample results differ significantly, then this strategy is almost ineffective.
Assuming that a strategy is found to fail due to off-sample data, a large loss caused by a few extreme markets, then a fixed stop-loss condition can be added to avoid this risk; if a strategy is found to fail due to too many trades, then we can tighten the trading logic slightly, reducing the frequency of trades.
It is important to note that if the trading logic itself is wrong at the beginning, it is difficult to modify it and get a profitable strategy, at this point it is necessary to re-examine one's own strategic thinking. In addition, in parameter optimization, the more parameters available, the better the applicability of the strategy. In many cases, your logic is misspelled.
Then, when you get a trading logic right, a strategy that makes money both inside and outside the sample, don't rush to trade on a real account. Especially for beginners, be sure to run a simulated account for at least 3 months first, if it is a mid-low frequency overnight strategy, it will take longer simulated trading time.
In a completely unknown future simulation scenario, the strategy is observed in the simulation trading, carefully checked whether the feedback signal matches the simulation trading signal, whether the price at the time of the order is deviated from the price at the time of the transaction, if the performance is in line with the expectations, then the strategy is effective.
Finally, after a long period of time testing the strategy, it is possible to put the strategy into real-world trading. Of course, in the process of quantifying trading, we must also remain vigilant and avoid extreme trends. In real-world trading, the expectation of the strategy is generally discounted, reaching the expected 50% is qualified.
Finally, it should be remembered that we also observe the effectiveness of the strategy as the trade proceeds, and reassess the strategy when we find that the strategy shows losses beyond what was expected. Because the market characteristics change, we form our current strategy mainly against the past market characteristics.
This article outlines the complete process of quantifying trading. In short, if you are an experienced investor, your block will be the computer language foundation, starting with visualization or mac, and then gradually moving to Python to practice and build strategies on this platform.
If you are a computer science student or an IT practitioner with strong programming skills, the obstacle will be your experience in market investing, and don't underestimate this.
The trading strategy is at the core of the entire lifecycle of quantitative trading. In the next section, we will explain in detail what the elements of a complete trading strategy are from the perspective of trading strategy architecture. This will help you build your trading strategy more comprehensively and take quantitative trading to a new level!
Try to write the trading strategy in this section in Malay language. 2 What is the most important performance indicator for quantitative transactional reassessment?
A complete strategy, in fact, is a set of rules that the trader sets for himself, it covers all aspects of the trade, and leaves no room for the trader's subjective imagination, every buying and selling decision, the strategy will give an answer. It includes at least strategy selection, variety selection, money management, ordering, extreme market response, trading mentality, etc.
From a hedge fund perspective, the mainstream trading strategies can be divided into trend trading, pair trading, one-basket trading, event driving, high-frequency trading, options trading, and so on, as shown below. Of course, the classification of strategies is not fixed.Figure 1-4 Classification of trading strategies
For beginners who are just starting out with quantitative trading, it is not necessary to start with so many notions, but step by step from the simplest ones. If only one quantitative trading strategy is recommended to get started, it is trend trading, because it is simple and effective. Believe that you can trade well even if you do not have a systematic study of financial knowledge.
Those who have traded should know that each variety has its own characteristics. Some varieties are very volatile, volatile, high volatility; some varieties are very temperate and smooth, fluctuating throughout the year in a certain range, low volatility.
Therefore, when choosing a trading variety, it is necessary to have the concept of volatility, varieties with high volatility, often it is easy to get out of a wave of good trend markets. For commodity futures, if it is a trend tracking strategy, try to choose industrial products, from the variety attributes, industrial products are often greater than agricultural products.
Different strategies to suit different markets, choosing the right trading varieties, is a very crucial start to the great project of futures trading. In an absolute sense, there are no absolutely good varieties and no absolutely bad varieties. Depending on the different investment style, and the different risk tolerance, it is necessary to adjust accordingly to your own criteria.
It's easy to lose money and hard to make money, and when you lose 50% of your account, you need 100% to make up for it. Even if you win 100% many times, you lose 100% once.
For the sake of simplicity, the above section also uses a straight-line strategy. In fact, many trading strategies based on traditional technical indicators usually have a maximum drawdown rate of more than 50% or more. But is a high-risk strategy completely useless?
Obviously not, the maximum drawdown rate can be completely controlled by money management. If you cut the position in half, the overall risk is also reduced by half, the maximum drawdown rate becomes 30%, if you cut the position in half again, the maximum drawdown rate becomes 15%, and in the end we get a strategy where the maximum drawdown rate is controlled at about 15%. This is a simple, crude money management method.
A good buy point is half the success, it can get you out of the cost zone quickly. But no one will ever be able to tell you what is right and wrong at this point. Opening a position is not the core of the trade.
Whether it is a short-term strategy or a long-term strategy, the ratio is not about who holds the position for a long time, but rather the risk-reward ratio. In other words, it affects the final outcome of the strategy's performance how to exit and when to make a profit. The exit method can also be divided into two types: stop-loss exit and stop-loss exit.
1. Type and method of ordering:There are many types and ways of ordering, such as: ordering with a queue price limit list, counter price, latest price, overprice, stop price, stop price, buy one, buy two, sell one, sell two, or first with a queue price, then with overprice, batch listing, or break up the large order into a single listing, or simply report the whole listing directly.
2 withdrawalIf the order has not been settled, it is either to continue waiting or to withdraw, the withdrawal condition is based on time, for example, within 10 seconds has not been settled, the price has moved away from the price of 10 jumps when the order was placed, it is to continue waiting, withdrawal or callback.
3 and follow upIf the order is still not settled, whether to continue the order. If the order is still not settled, whether to continue the order at the latest price, or the counterparty price, or the drop in the stop price, or whether to continue the order.
4, the price of the coin fellWhat happens when the current order signal appears, just when the price of the order has dropped. What happens when the order is in the queue, if no transaction has occurred.
5, collective biddingI'm not sure if I want to participate or not, how to participate.
6 o'clock at nightSome commodity futures have a night shift from 21:00 to 02:30 the next day, which is not done, either manually or by computer.
7 major festivalsThe position does not need to be reserved before the extended holidays of major festivals.
First, the short-term price fluctuations. How to deal with instant price falls, consecutive price falls, the Ural Finger event, the Black Swan market price trampling event, etc.?
2 Liquidity risk If you don't have the order quantity you want, but you need to get the order in time, especially if the liquidity of the non-core contract is poor, your order is easy to shock the market, and the slippage point is large, how to deal with it?
3 Changes in breed rules Commodity futures are very sensitive to these changes, especially short-term strategies.
4 Risks to the trading environment For example: sudden power outages, network disruptions, computer failures, software crashes, money transfer suspensions, natural disasters, etc. How to respond when they occur.
The probability of this happening is very small, if not impossible. But if something can happen, it will happen. It is very important to make these assumptions and to take precautions.
The three main emotions that are common in trading are greed, fear, and greed. Investors need a strong trading psychology to control and even exploit these three emotions at different stages.
A transaction must be preceded by an overall expectation of the future, including market expectations and psychological expectations of the variety. Market expectations refer to a clearer goal for the position and future direction of the market, while varietal expectations refer to the trading opportunities and risks of the variety in its current position.
The whole process of real-time trading is a process of continuous analysis, correction and execution, with less time between transactions, but more tracking and patience. This is a comprehensive process of examining the mindset, testing the human nature, and the traders' various habits will be displayed and amplified in the process of trading. Only continuous learning and summarizing the lessons of experience, continuous practice, can overcome the commonality of thought and psychological weaknesses of human nature.
In summary, the so-called trading strategy, in fact, has its perfect side and its flawed side. When we measure whether a trading strategy is reasonable, we should not only look at its perfect side or its flawed side, but also the integrity of a more comprehensive analysis strategy.
Finally, based on the characteristics of the strategy, in combination with one's own personality and financial situation, to measure whether the strategy is suitable for you, if it is suitable for you, to fully evaluate how likely you are to stick to it, the worst outcome is to plan in advance, if the worst side you want to do well, then the probability of executing is relatively high.
Remember, in trading, confidence comes from your heart's acceptance, and confidence comes from the right trading ideas!
This is the last chapter of the first one, and in the next chapter we will go on to explain more about quantitative trading tools, including: an overview of quantitative trading tools, how to configure quantitative trading systems, common API explanations, how to write strategies on quantitative trading systems.
1. Should a trend trading strategy choose a high volatility variety or a low volatility variety? 2 How many types of trading orders are there?
In the previous chapter, we have learned about the concepts of quantitative trading and have a basic understanding of quantitative trading. So what tools are available on the market to quantify trading and how should we choose according to our needs?
Open source and commercial software Domestic quantitative trading tools can generally be divided into two broad categories: open source software and commercial software. The so-called open source software can be understood as software whose source code is open and can be downloaded directly; commercial software generally refers to closed source software maintained and operated by commercial companies, usually for a fee.
First of all, open source software has a strong flexibility and is completely free, users can basically use this software to implement any function, whether it is a medium-low frequency trading strategy, option strategy or option strategy, can be implemented through custom modules, since the user masters the source code of this software, can understand every corner of the software, so it is more reliable and secure.
Although open source software has many advantages, it is not very friendly to beginners of quantitative trading, you need to systematically learn a standard programming language, such as Python, Java or C++. From the beginning to the end, its difficulty is understandable, sometimes debugging can make you doubt your life. And unlike commercial software, there is a specialized technical customer service that answers questions immediately.
So, from a learning point of view, it is recommended to start with the simplest commercial software, even though it is paid, but if the strategy is profitable, the software costs are only a fraction of the profit. Secondly, commercial software is generally a team in maintenance and its maturity is definitely much stronger than open source software.
There are dozens of commercial software that can do quantitative trading in the country, such as: Interactive Broker, which is both professional and comprehensive and has many products, can process large amounts of data, APAMA, which is suitable for high-frequency trading, supports C++ interface, SPT, which is very efficient, focuses on transaction execution and wind-control drilling quantization and for individual traders.Figure 2 - 1 Comprehensive assessment of the mainstream quantitative platforms in the country
Although this is commercial software, it is also used as a standard programming language or scripting language, rather than directly using free and secure open source software.The website is www.fmz.com│ as a knock on the door to quantitative trading learning│
The inventor's quantification tool is friendly to small and small, even if you are zero-based, and can be quantified based on the specific charm of the work in it. The tool is designed for high-frequency trading, with strict requirements in performance and security. It supports high-frequency strategies, arbitrage strategies, trend strategies.
Quantification tools are very simple to use, you just need to go to the website to create your own quantification strategy. You can log on to the inventor's official website of the quantification tool, register and log in, click on the control center can be used ((as shown below), similar to the current comparison of fire buzz, you can publish your own short video after registering, while the quantification tool log on to design your own quantification trading strategy.
Figure 2-2 FMZ is a quantity trading platform
The programming of the quantitative tool will have a centralized functional area, the functional area mainly consists of the control center in the upper left corner, which is the core function of the quantitative tool. After clicking, you can write trading strategies and policy retrieval, set up trading varieties, create management strategies for the trustee of the robot, create specific quantitative trading robots.
Figure 2-3 FMZ Quantitative Trading Platform admin page after landing
To reduce the threshold for users, the official community has released many video tutorials to help quantitative trading beginners get started quickly; at the same time, thousands of official and third-party trading strategies are collected in Strategy Square, which is free and open, so that everyone can copy and learn.
In addition, in the strategy editor interface, classic strategy examples are also configured, allowing you to directly use the strategy code with a click, easily experiencing the core process of the entire quantified transaction, even the small white user can immediately learn and follow!
Simulated trading is also an essential link before the real gold and silver market. The simulated trading tool complies with the rules of the exchange and is completely free, the simulated time, price, order volume, etc. are captured in real time with the real market, which is highly consistent with real trading.
Whether it is open source software or commercial software, there are no advantages and disadvantages, and there is no perfect quantitative trading tool, each tool has its own focus, the most important thing is to choose the right tool according to your needs. Commercial software requires payment, it is better in terms of services, etc., and may be more suitable for beginners in the industry. If you have been in the industry for a long time, have accumulated a lot of experience, or need to implement more complex trading strategies, open source software is a better choice.
How to use the tool? Just like when we bought a new phone, the first time we need to do a simple startup setup, the quantitative tools also need to do the basic setup configuration, in the next section we will take you to configure the inventor of the inventor of the quantitative trading tool. Open the first door of quantitative trading, including: adding exchanges, adding custodians, creating trading strategies, creating quantitative robots, etc. After completing the basic configuration, you can officially write the first article of your own quantitative strategy.
1.What are the two main categories of quantitative trading instruments? 2 What are the most commonly used quantitative programming languages?
The first thing to do when developing a quantitative trading strategy is to configure the trading tool, what is it for?
The configuration is divided into the introductory learning simulation trading mix and the real-time trading configuration, which we mainly focus on domestic commodity futures, and other categories of quantitative investments because of the domestic specific situation without making recommendations and introductions, but the operating process is the same, only the configuration process is different.
Adding an exchange is the first step in the entire configuration process, the specific process is described in the diagram below. In this step, we need to emphasize that adding an exchange is not difficult.Figure 2-4 FMZ QT platform registration and adding exchanges steps
For real-time quantification trading, we mainly use domestic futures trading varieties, currently the main service object of inventor quantification is also the domestic futures exchange. For friends who do foreign exchange, inventor quantification can be used as a learning platform, because forex quantification trading on platforms such as mt5 has already appeared, but is more professional.
The following issues need to be taken into consideration when configuring the real-time platform: Since the inventor's quantification tool supports multiple trading markets, it is necessary to configure the commodity futures first by selecting the traditional futures platform in step 1; in step 2, you need to fill in the futures company you are opening, giving you the futures account and password.
The inventor of the quantification tool, using the CTP protocol, supports all domestic futures companies, when configuring the physical disk, there will be no link failure, unless the account and password are wrong, so beginners should pay attention to the account and password to check clearly.Figure 2-5 FMZ Quantitative trading platform added futures exchanges
For friends who are new to commodity futures, I recommend that you simulate trading for a while, because the process of developing a quantitative trading strategy requires constant testing, debugging, optimization. Just like driving, starting is definitely a few months of groping in the driving school, and after checking the certificate, you will be on the road again.
SimNow is a financial simulation simulation trading platform designed for investors in the past. The product simulates the trading and settlement rules of various exchanges.Figure 2-6 FMZ Quantitative Trading Platform admin page after landing
The strategy library is the place where the code is stored, it is equivalent to our quantitative trading strategy repository. It is mainly divided into two functions: strategy writing and analogue review. The strategy writing area is the main work area of our future development strategy (see figure below). Many beginners are often blocked by various codes and find it very difficult, in fact, just a little bit of attention can be used to learn these codes, do not be psychologically burdened.Figure 2-7 Steps to creating a strategy
The quantity trading robot is the executor of the trading strategy. Once the strategy is created, create a robot that can automatically help you execute every trading logic in the strategy code, as well as buy and sell operations such as opening, placing, withdrawing and so on.Figure 2-8 Steps to create a robot
In the above process, in addition to the fact that the first step is different from the real and the analog, the following steps are the same. The entire quantization tool is configured, the trading robot is operational, and the transaction will be done according to the specific conditions of the strategy.
Although it only takes three simple steps to achieve quantified trading, you may find that it is easy to add an exchange and create a quantified trading robot. However, it is not so easy if you want to implement a viable trading strategy. In the next section, we will take you to learn the API commonly used in quantified trading, to prepare you for writing a viable trading strategy.
First, try adding an exchange. Try writing a trading strategy in this section.
For many non-IT people, what exactly is an API? API ≈ I don't understand. In this section, we will use colloquial topics, what exactly is an API, and an introduction to the API commonly used in inventors' quantitative tools.
If you search the web, you will get the following results: API (Application Programming Interface) are a set of predefined functions that are intended to provide applications and developers with the ability to access a set of procedures based on a software or hardware without having to access the source code or understand the details of the internal mechanisms.
In fact, in our daily life, we have many scenarios similar to API, for example: you go to a restaurant to eat, you just need to look at the menu and order the food, you do not need to know exactly how it is made.
If you need to know how to get the current price, you don't need to know how to get it. You just need to write the OPEN key in the code editor and use it directly.
Before discussing the Mac language API, let's first look at what the commonly used code structure is and what its functions are made up of, which will help you better understand the API.Figures 2-9 Examples of the Malay language
The code is shown in the picture above: AA in purple is the variable, and the variable is the quantity that can be changed, which is the same as our algebra in middle school. If you assign the opening price to AA, then AA is the opening price; if you assign the highest value to AA, then AA is the highest price. Of course AA is just a custom name, you can also define BB.
The green onion: = onion is the meaning of the attribute, i.e. the value of the onion: = onion on the right is given to the variable on the left.
The orange code is the inventor's quantification tool's grain language API, note that the OPEN in the first line is the API for obtaining the closing price, which can be used directly; the MA in the second line is the API for obtaining the even line, which requires the transmission of 2 parameters, that is, you need to tell the inventor's quantification tool what kind of even line you need: if you want to get the 50-cycle even line calculated with the opening price, then you can write: MA ((OPEN, 50); note that there is an English comma between the two parameters.
The yellow slide/slide is the annotation, followed by the blue Chinese slide is the annotation content, which are all self-reviewed, and are used to suggest what the line of code means. The program does not handle any annotations when running. Note that before the annotation, each line of code has an English decimal point at the end of the line.
With a basic understanding of the code structure, we bring you some of the most commonly used languages below, which we will use more often in the future. OPEN buys the latest opening price of the K line Example: AA:=OPEN; get the latest K-line opening price and assign the result to AA
HIGH can get the highest price on the latest K line Example: AA:=HIGH; gets the highest price of the latest K line and assigns the result to AA
LOW to get the lowest price on the latest K line Example: AA:=LOW; get the lowest price on the latest K-line and assign the result to AA
The CLOSE button gets the closing price of the latest K-line, when the k-line in the disk is not finished, and gets the latest price Example: AA:=CLOSE; get the closing price of the latest K line and assign the result to AA
VOL has access to the latest K-Line transactions Example: AA:=VOL; obtains the latest K-line transaction volume and assigns the result to AA
REF ((X,N)) refers to the value of X before N cycles. Example: REF ((CLOSE,1); get the opening price of the upper root K line
MA ((X,N) is the simple moving average over N cycles for X Example: MA ((CLOSE,10); // Obtains the 10-period mean of the latest K-string
CROSSUP ((A,B)) indicates that when A crosses B from the downward direction, it returns 1 ((Yes) and 0 ((No) if not Examples: CROSSUP ((CLOSE, MA ((C,10)) // Closing price is the average price over 10 cycles
CROSSDOWN ((A,B)
BK is buying a stock. Examples: CLOSE>MA ((CLOSE,5), BK; // Closing price is greater than 5 cycle average, buy to open position
SP is closing. Examples: CLOSE
SK is selling the open position. Examples: CLOSE
BP to buy the equity Examples: CLOSE>MA ((CLOSE,5), BP; // Closing price is greater than 5 cycle average, buy to break even
BPK is buying a flat and buying an open position (against doing more) Examples: CLOSE>MA ((CLOSE,5), BPK; // Closing price is greater than the 5-cycle average, flatten the empty position, then buy the position again.
SPK is selling a flat position and selling an open position. Examples: CLOSE
CLOSEOUT flattening all holdings is recommended for use in a plus-minus model. Example: CLOSEOUT; flattening all positions in all directions.
Before discussing the JavaScript language API, let's first look at what the commonly used code structure is and what functions it has, which will help you better understand the API.Figure 2-10 JavaScript code examples
The code is shown in the picture above:
In the JavaScript language, the creation of a variable is usually called a declaration of a variable. Red code, we use the var keyword to declare the variable, and the variable name is orange code:
In the JavaScript language, an equal value is assigned, i.e. the value of the right hand side of
The green code is the JavaScript language API, and when we call it, it's actually calling a function in an exchange object. Note that the dot after the blue code is also a fixed format. The function here is the same as the function we learned in middle school.
After a few examples and a basic understanding of the basic structure of code, we'll show you a few common JavaScript APIs that you'll be using in the future.
SetContractType Set the type of contract, which is the variety you want to trade
Example: exchange.SetContractType ((
GetTicker button to get the Tick data Example: exchange.GetTicker ((); // get the data from Tick
GetRecords tool to retrieve data from the K-line Example: exchange.GetRecords ((); // get the data from the K-line
Buy and buy Examples: exchange.Buy ((5000, 1); // Buy one hand at the price of 5000 yuan
Sell and buy Examples: exchange.Sell ((5000, 1); // Sell one hand at a price of 5000 yuan
GetAccount tab to get account information Example: exchange.GetAccount ((); // get account information
GetPosition bar to get hold information Example: exchange.GetPosition ((); // get hold of the information
SetDirection bar to set more than one blank list type
Examples:
exchange.SetDirection ((
Logging a message in the log
Example:Log ((
Sleep button pauses the program for a while Example: Sleep ((1000); // pauses the program for 1 second
Maybe some of the partners will have doubts, there are so many APIs, how to remember? In fact, all of these do not need you to memorize the hardback, inventors of quantitative official have a detailed set of API documents. Just like searching dictionaries, when you use, you need to directly check what is done. No need to be intimidated by the initial knowledge of content such as code.
These are the most commonly used APIs in quantitative trading, which basically include: obtaining data, calculating data, placing an order to buy and sell, enough to handle a simple quantitative trading strategy, of course if you want to write a more complex strategy, you need to go to the inventor's quantitative tools website to get it.
1, try to write a Mac language 5-cycle even-line sentences with 10 cycles even-line sentences. Try getting your account information from GetAccount in JavaScript and print it to the log using Log.
Programming is like assembling Lego blocks, APIs are like building blocks, and the process of programming is to assemble Lego parts into a complete toy. In the next section, I will take you through the process of assembling a complete quantitative trading strategy using the Mac language API.
After learning the previous few sections, you can now finally write a quantitative trading strategy manually. This will be the most important step from manual trading to quantitative trading. In fact, it's not that mysterious, writing strategies is nothing more than translating your ideas into code. This section will implement a quantitative trading strategy from scratch, familiarizing you with how to write strategies on inventors' quantitative systems.
The first step is to open the website of the developer's quantification tool, then click on the policy library tab, click on the new policy tab, it is important to note that before writing code, you need to select the Mac language or JavaScript language in the programming language drop-down menu, of course the platform also supports Python, C++ and visualization languages.
In previous chapters, a strategy for price breakouts has been introduced; that is, buy if the price is above the last 10 days average and sell if the price is below the last 10 days average. However, while prices can intuitively reflect the state of the market, there are many false breakout signals; so we will upgrade and improve this strategy.
First, a larger periodic averagely is selected to judge the trend direction, which has at least filtered out almost half of the false breakout signals, and the periodic averagely, although sluggish, is more stable; then, in order to increase the success rate of the entry again, a condition is added that the periodic averagely is at least upward; finally, the relative position relationship of the price, short-term averagely, and long-term averagely forms a complete trading strategy.
With these strategic ideas and thoughts, we can try to construct strategic logic. The logic here is not to let you calculate the laws of the universe, it's not that complicated. It's just to put the previous strategic ideas into words.
Multi-headed: If there is no position at the time, and the closing price is higher than the short-term average, and the closing price is higher than the long-term average, and the short-term average is higher than the long-term average, and the long-term average is higher.
Opening the bargain: If there is no position at the time, and the closing price is below the short-term average, and the closing price is below the long-term average, and the short-term average is below the long-term average, and the long-term average is downwards.
Multiple heads: If there are multiple orders currently held and the closing price is below the long-term average, or the short-term average is below the long-term average, or the long-term average is down.
Standing on empty: If there is a current hold on an empty order and the closing price is higher than the long-term average, or the short-term average is higher than the long-term average, or the long-term average is higher.
This is the logical part of the whole quantitative trading strategy, so if we convert the written version of the strategic logic into code, it will include: getting the market, calculating the indicator, placing the buy and sell order, these three steps.
The first is to get the market, in this quantitative trading strategy, we just need to get the closing price, then in Ma, the API for getting the closing price is: CLOSE, that is, you just need to write CLOSE in the code, and you have already obtained the closing price of the latest K line.
And then we calculate the indicators, and in this quantitative trading strategy, we have two techniques together, which are the short-term averages and the long-term averages, and we assume that the short-term averages are 10-cycle averages and the long-term averages are 50-cycle averages, so how do we use the code to represent 10-cycle averages and 50-cycle averages?Figure 2-11 The code of the Ma language strategy
In manual trading, we can see at a glance whether the 50-period mean line is up or down, but how do we express it? Think carefully, to determine whether the mean line is up is that the mean line of the current K line is 50 times larger than the mean line of the upper root K line, and the mean line of the upper root K line is 50 times larger than the mean line of the upper root K line?Figure 2-12 Mean-language judgments of even-line codes
Note that in the 8th and 9th lines of the above diagram, the red code is YANDY, which in the Malay language means Yand and Yand. For example, the 9th line translates into Chinese as: If the 50-periodic equator of the current K-line is greater than the 50-periodic equator of the upper root K-line, and the 50-periodic equator of the upper root K-line is greater than the 50-periodic equator of the upper root K-line, then the value is calculated as Yand; otherwise, the value is calculated as Yand and the result is Yand, and the value is assigned to Yand MA50_ISUP Yand.
The final step is to buy and sell the order, and just behind the buy and sell logic code, the buy and sell operation can be performed by calling the inventor's quantification tool's buy and sell API.Figure 2-13 Chinese language trading codes
Notice that in the 13th and 14th lines of the above diagram, the red-orange code is OR, which in the Malay language means "orange" or "orange"; for example, the 13th line is translated into Chinese as: If the closing price of the current K line is less than the 50-cycle homogeneous of the current K line, or the 10-cycle homogeneous of the current K line is less than the 50-cycle homogeneous of the current K line, the calculation value is "orange" and is immediately listed; otherwise the calculation is "orange" and nothing is done.
Please note: the AND and OR keys are logical operators in the Maic language: The final condition is that all the conditions are positive, and the final condition is positive. If any one of the conditions is true, then the final condition is true.
This is the entire process of writing a trading strategy in the inventor's quantitative tool, and in total, it takes three steps: from having a strategy idea, to conceiving the strategy and describing the logic in words, and finally implementing the complete trading strategy in code. Although this is a simple strategy, the specific implementation process differs from the complex strategy, only the algorithms and data structures of the strategy are different. Therefore, it is necessary to understand the process of quantitative strategy in this section to conduct research and practice in the inventor's quantitative tool.
I am trying to implement the strategies in this section. 2, Add the stop-loss function on the basis of this section's strategy.
In the development of quantitative trading strategies, programming languages are like weapons, and a good programming language can help you do half the work. For example, Python, C++, Java, C#, EasyLanguage, Mac, etc. are the most commonly used languages in quantitative trading.
In Chapters 1 and 2, we learned about the basics of quantitative trading and how inventors use quantitative tools, and in this chapter we will discuss the specific implementation of trading strategies. To implement trading strategies, it is necessary to master a programming language. This section introduces the main programming languages used in quantitative trading, as well as the characteristics of each programming language.
Before learning a programming language, you first need to understand the concept of a programming language. A programming language is a language that humans and computers can understand. It is a standardized form of communication code. The purpose of a programming language is to use human language to control the computer and tell the computer what to do.
Just as our parents taught us to speak openly as children, they also taught us how to understand others.
Hailhydra2Good article!
The vacuum is quantized mark