Home > Java > javaTutorial > How does Java implement a trading strategy based on the active flow of funds?

How does Java implement a trading strategy based on the active flow of funds?

王林
Release: 2023-04-18 18:34:27
forward
1083 people have browsed it
1. Summary

The price is either up or down. In the long run, the probability of price increase or decrease should be 50% each. To correctly predict future prices, you need to obtain all factors that affect prices in real time. , then give each factor a correct weight, and finally make an objective and rational analysis. Listing all the factors that affect price would fill the entire screen.

Summary: global economic environment, national macro policies, related industrial policies, supply and demand relations, international events, interest rates and exchange rates, inflation and deflation, market psychology, unknown factors, etc. Prediction has become a huge and impossible task. So very early on, I understood that the market was unpredictable. Then all predictions in the market have become assumptions, and trading has become a game of probability, which is interesting.

2. Why use capital flow

Since the market cannot be predicted, is it really indifferent? No, all macro and micro factors have been reflected in the price, which means that the price is the result of the interaction of all factors. We only need to analyze the price to make a complete trading strategy. How does Java implement a trading strategy based on the active flow of funds?

Think carefully first, why does the price increase?

You may say that it’s because: the country’s policy support for related industries, the country of origin is experiencing heavy rain, the international trade war, MACD has a golden cross, others are buying it, etc. Of course, these may all be That's right. With the benefit of hindsight, you can always see the reasons that drove prices higher.

In fact, the rise and fall of prices is similar to a rising tide that lifts all boats. The rise in prices cannot be separated from the promotion of funds. If there are more buyers than sellers on the market, the price will rise. On the other hand, if there are more sellers than buyers, the price will fall. With this concept, we can give reasonable expectations for future price trends based on the supply and demand relationship reflected by the net flow of funds.

3. Principle of Fund Flow

Different from traditional analysis, capital flow analysis analyzes which transactions are the active inflows of funds and which transactions are the active inflows of funds based on the transaction data of a sequence over a period of time. Outflow. Then, by subtracting the active outflow volume from the active inflow volume during that time period, you can know the net capital inflow during that time period. If the net inflow of funds is positive, it means that the supply of this product exceeds demand; if there is a net outflow of funds, it means that the supply of this product exceeds demand.

How does Java implement a trading strategy based on the active flow of funds?

#After reading this, some people may wonder that in actual transactions, a transaction is completed only when someone buys and someone sells. Transaction orders must have as many sales as there are purchases, and the inflow and outflow of funds must be equal. Where do the capital inflows and outflows come from? In fact, strictly speaking, each buy order must correspond to a corresponding sell order, and the capital inflow and capital outflow must be equal. If we want to calculate which orders were actively bought and which orders were actively sold, we can only use a compromise method, using bar data and based on trading volume and price.

4. Capital flow calculation method

Changes in capital flow accurately correspond to real-time market behavior. By integrating bar data, the net capital flow is calculated in real time. There are two algorithms for calculating the active flow of funds:

  • The first one, if the transaction price of the current order is executed at the counterparty price or overprice, the purchase transaction price>= The first selling price means that the buyer is more willing to complete the transaction at a higher price, which takes into account the active inflow of funds.

  • Second, if the current transaction price > the last transaction price, then it can be understood that the current transaction volume actively pushes up the price increase, that is, it is included in the capital initiative inflow.

How does Java implement a trading strategy based on the active flow of funds?

Take the second algorithm above as an example:

The closing price of a certain variety at 10:00 is 3450. The closing price at 11:00 is 3455, then we include the trading volume from 10:00 ~ 11:00 as active capital inflow. Otherwise, it will be included in the active outflow of funds. This article is based on the second method and adds the factor of price fluctuation. By comparing the closing prices of the previous and previous bars, the trading volume * fluctuation range of the rising or falling bar is included in a sequence, and then further based on the sequence. Calculate the active inflow ratio of funds.

5. Trading logic

This article describes the capital flow in the futures market from the perspective of "volume", and establishes a trading model to judge short-term price trends by analyzing bar data in real time. Under normal circumstances, capital flow and price trends can be divided into four basic situations:

  • #The price rises, and at the same time, there is a net inflow of capital per unit time: In this case, it is strong. The probability that the price will continue to rise in the future is greater;

  • The stock price rises, and at the same time there is a net outflow of capital initiative per unit time: In this case, it is considered to be medium-strong, and the speed of future price rises will be significantly weakened;

  • The stock price falls, and at the same time, there is a net inflow of capital initiative per unit time: In this case, it is a weak point, and the probability of the price continuing to fall in the future is greater;

  • The stock price falls, and at the same time, there is a net outflow of funds per unit time: In this case, it is a medium-weak situation, and the speed of future price decline will be significantly weakened; How does Java implement a trading strategy based on the active flow of funds?

The main variables are as follows:

  • Previous low point (ll)

  • Previous high point (hh )

  • Active buying (barIn)

  • Active selling (barOut)

  • The ratio of active inflows to active outflows (barRatio)

  • Opening threshold (openValve)

  • Current position (myAmount)

  • Last K-line closing price (close)

#Entry and entry conditions A good quantitative trading strategy requires not only Stable income and the ability to control risks to avoid large losses when a small probability occurs. Here we use the strategy of tracking active capital flows and analyze the market direction of commodity futures with the help of short-term price predictions to achieve high returns and low risks. The steps of the strategy are as follows: How does Java implement a trading strategy based on the active flow of funds?

  • Open a long position: If there is currently no position and barRatio > openValve, open a long position;

  • Short position opening: If there is currently no position, and barRatio

  • Long position closing: If there is currently a long position, and close < ll, sell to close the position;

  • Short position close: If you currently hold a short position and close > hh, buy to close the position;

6. Write strategy source code

Get and calculate data

function data() {
    var self = {};
    var barVol = [];
    var bars = _C(exchange.GetRecords); //获取bar数据
    if (bars.length < len * 2) { //控制bar数据数组的长度
        return;
    }
    for (var i = len; i > 0; i--) {
        var barSub_1 = bars[bars.length - (i + 1)].Close - bars[bars.length - (i + 2)].Close; //计算当前收盘价与上个bar收盘价的价差
        if (barSub_1 > 0) { //如果价格涨了,就在数组里面添加正数
            barVol.push(bars[bars.length - (i + 1)].Volume * (bars[bars.length - (i + 1)].High - bars[bars.length - (i + 1)].Low));
        } else if (barSub_1 < 0) { //如果价格跌了,就在数组里面添加负数
            barVol.push(-bars[bars.length - (i + 1)].Volume * (bars[bars.length - (i + 1)].High - bars[bars.length - (i + 1)].Low));
        }
    }
    if (barVol.length > len) {
        barVol.shift(); //释放多余的数据
    }
    self.barIn = 0;
    self.barOut = 0;
    for (var v = 0; v < barVol.length; v++) {
        if (barVol[v] > 0) {
            self.barIn += barVol[v]; //合并全部主动流入的资金
        } else {
            self.barOut -= barVol[v]; //合并全部主动流出的资金
        }
    }
    self.barRatio = self.barIn / Math.abs(self.barOut); //计算主动流入资金与主动流出资金的比值
    bars.pop(); //删除未结束的bar数据
    self.close = bars[bars.length - 1].Close; //获取上根K线的收盘价
    self.hh = TA.Highest(bars, hgLen, 'High'); //获取前高
    self.ll = TA.Lowest(bars, hgLen, 'Low'); //获取前低
    return self;
}
Copy after login

Get bar data directly through the GetRecords method in the inventor's quantification API. Contains the highest price, lowest price, opening price, closing price, trading volume, and standard timestamp. If the latest transaction price is greater than the last transaction price, then the latest transaction volume * (highest price - lowest price) will be included in the active buying; if the latest transaction price is lower than the last transaction price, then the latest transaction volume * (highest price - lowest price) will be included in the active buying; The trading volume* (highest price - lowest price) is included in active selling;

Get position data

function positions(name) {
    var self = {};
    var mp = _C(exchange.GetPosition); //获取持仓
    if (mp.length == 0) {
        self.amount = 0;
    }
    for (var i = 0; i < mp.length; i++) { //持仓数据处理
        if (mp[i].ContractType == name) {
            if (mp[i].Type == PD_LONG || mp[i].Type == PD_LONG_YD) {
                self.amount = mp[i].Amount;
            } else if (mp[i].Type == PD_SHORT || mp[i].Type == PD_SHORT_YD) {
                self.amount = -mp[i].Amount;
            }
            self.profit = mp[i].Profit;
        } else {
            self.amount = 0;
        }
    }
    return self;
}
Copy after login

Obtained through the GetPosition method in the inventor's quantitative API Basic position data, and further process these basic data. If you currently hold a long order, then return the positive position quantity; if you currently hold a short order, then return the negative position quantity. The purpose of this is to facilitate the calculation of the logic of opening and closing positions.

Place an order and trade

function trade() {
    var myData = data(); //执行data函数
    if (!myData) {
        return;
    }
    var mp = positions(contractType); //获取持仓信息
    var myAmount = mp.amount; //获取持仓数量
    var myProfit = mp.profit; //获取持仓浮动盈亏
    if (myAmount > 0 && myData.close < myData.ll) {
        p.Cover(contractType, unit); //多头平仓
    }
    if (myAmount < 0 && myData.close > myData.hh) {
        p.Cover(contractType, unit); //空头平仓
    }
    if (myAmount == 0) {
        if (myData.barRatio > openValve) {
            p.OpenLong(contractType, unit); //多头开仓
        } else if (myData.barRatio < 1 / openValve) {
            p.OpenShort(contractType, unit); //空头开仓
        }
    }
}
Copy after login
7. Strategy features

Features:

Few core parameters: The model design idea is clear and there are only three core parameters. The space for optimization is small and overfitting can be effectively avoided. Strong universality: The strategy logic is simple and has high universality. It is suitable for most varieties except agricultural products and can be combined with multiple varieties.

Improvement:

Add position conditions: One-way (stock) market capital flow can define the inflow or outflow of capital based on price rises and falls, trading volume and other factors . However, since this strategy does not include the condition of position, the statistics of active fund flows may be distorted.

Add standard deviation conditions: Relying solely on the flow of funds as the conditions for opening a position may cause frequent false signals, resulting in frequent opening and closing of positions. False signals are filtered out by counting the average of net fund outflows within a specified period, plus the standard deviation.

Complete strategy source code:
/*backtest
start: 2016-01-01 09:00:00
end: 2019-12-31 15:00:00
period: 1h
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
*/

var p = $.NewPositionManager(); //调用商品期货交易类库

//持仓数据处理
function positions(name) {
    var self = {};
    var mp = _C(exchange.GetPosition); //获取持仓
    if (mp.length == 0) {
        self.amount = 0;
    }
    for (var i = 0; i < mp.length; i++) { //持仓数据处理
        if (mp[i].ContractType == name) {
            if (mp[i].Type == PD_LONG || mp[i].Type == PD_LONG_YD) {
                self.amount = mp[i].Amount;
            } else if (mp[i].Type == PD_SHORT || mp[i].Type == PD_SHORT_YD) {
                self.amount = -mp[i].Amount;
            }
            self.profit = mp[i].Profit;
        } else {
            self.amount = 0;
        }
    }
    return self;
}

//行情数据处理函数
function data() {
    var self = {};
    var barVol = [];
    var bars = _C(exchange.GetRecords); //获取bar数据
    if (bars.length < len * 2) { //控制bar数据数组的长度
        return;
    }
    for (var i = len; i > 0; i--) {
        var barSub_1 = bars[bars.length - (i + 1)].Close - bars[bars.length - (i + 2)].Close; //计算当前收盘价与上个bar收盘价的价差
        if (barSub_1 > 0) { //如果价格涨了,就在数组里面添加正数
            barVol.push(bars[bars.length - (i + 1)].Volume * (bars[bars.length - (i + 1)].High - bars[bars.length - (i + 1)].Low));
        } else if (barSub_1 < 0) { //如果价格跌了,就在数组里面添加负数
            barVol.push(-bars[bars.length - (i + 1)].Volume * (bars[bars.length - (i + 1)].High - bars[bars.length - (i + 1)].Low));
        }
    }
    if (barVol.length > len) {
        barVol.shift(); //释放多余的数据
    }
    self.barIn = 0;
    self.barOut = 0;
    for (var v = 0; v < barVol.length; v++) {
        if (barVol[v] > 0) {
            self.barIn += barVol[v]; //合并全部主动流入的资金
        } else {
            self.barOut -= barVol[v]; //合并全部主动流出的资金
        }
    }
    self.barRatio = self.barIn / Math.abs(self.barOut); //计算主动流入资金与主动流出资金的比值
    bars.pop(); //删除未结束的bar数据
    self.close = bars[bars.length - 1].Close; //获取上根K线的收盘价
    self.hh = TA.Highest(bars, hgLen, 'High'); //获取前高
    self.ll = TA.Lowest(bars, hgLen, 'Low'); //获取前低
    return self;
}

//交易函数
function trade() {
    var myData = data(); //执行data函数
    if (!myData) {
        return;
    }
    var mp = positions(contractType); //获取持仓信息
    var myAmount = mp.amount; //获取持仓数量
    var myProfit = mp.profit; //获取持仓浮动盈亏
    if (myAmount > 0 && myData.close < myData.ll) {
        p.Cover(contractType, unit); //多头平仓
    }
    if (myAmount < 0 && myData.close > myData.hh) {
        p.Cover(contractType, unit); //空头平仓
    }
    if (myAmount == 0) {
        if (myData.barRatio > openValve) {
            p.OpenLong(contractType, unit); //多头开仓
        } else if (myData.barRatio < 1 / openValve) {
            p.OpenShort(contractType, unit); //空头开仓
        }
    }
}

//程序主入口,从这里启动
function main() {
    while (true) { //进入循环
        if (exchange.IO("status")) { //如果是开市时间
            _C(exchange.SetContractType, contractType); //订阅合约
            trade(); //执行trade函数
        }
    }
}
Copy after login
8. Strategy backtest

Strategy configuration: How does Java implement a trading strategy based on the active flow of funds? Backtest performance: How does Java implement a trading strategy based on the active flow of funds? How does Java implement a trading strategy based on the active flow of funds?

The above is the detailed content of How does Java implement a trading strategy based on the active flow of funds?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template