The resource loading... loading...

Binance Strategy Two: Removing highs and lows

Author: Quantification of district classes, Date: 2020-04-09 21:44:22
Tags: Binance

Thank you for the FMZ Open Strategy, thank you for the Guards support! I've made two changes myself: 1, because many friends default to 10 times 20 times leverage, and the strategy is a full-position mode, a coin boom position, will be destroyed. 2. If there is a super-high over-fall in the coin pool, for example, a unique coin, it is easy to drag everyone down, the overall strategy is easy to fail. Therefore, when calculating the index, I remove a highest score and remove a low score, the resulting index is fairer. In addition, the government has announced that it will reinstate the special currency, which will be available for purchase in the future. Please note: Due to limited conditions, this policy has not been retested and is for reference only, no liability in case of loss!

This is important!

  • I'm sure you'll want to read this study first.https://www.fmz.com/digest-topic/5294■ Understand a range of issues such as strategy principles, risks, how to screen trades, how to set parameters, opening positions and the ratio of total capital.
  • The previous research report needs to be downloaded and uploaded to your own research environment. The actual modification runs again. If you have read this report, you have recently updated the latest week's data.
  • The strategy cannot be directly retested, it needs to be retested in the research environment.
  • The policy code and default parameters are for research purposes only, and real-time operation requires caution and risk.
  • The code is open, you can modify it yourself, if there are any problems, welcome feedback, it's best to join the Inventor Binance community (there are ways to join the research report)
  • The strategy needs to run in a full-stock mode.The strategy supports Binance, the default trading pair and the K-line cycle when creating the robot, the strategy does not use the K-line.

The Principles of Strategy

Coins that are above the Bitcoin price index and below the Bitcoin price index, the greater the deviation, the larger the position. The strategy is not hedged and BTC can also be added to the trading pair. Performance in the last two months.img

Strategic logic

1. update the market and account holdings, the first run will record the initial price (newly added currencies are calculated according to the time of joining) 2. update the index, the index is the coin-bitcoin price index = mean ((sum)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 3. Judging by the deviation index, doing more work, judging the position according to the deviation size 4. The order and quantity of the order will be determined by the Ice Mountain commission, according to the transaction price of the counterparty (buy and sell at the same price).I'm not sure if this is a good idea, but I'm going to try to get a copy of this book, and I'm going to get a copy of this book. 5.再次循环

Policy parameters

img

  • Trade_symbols: Currencies traded, needing to be screened by the research platform themselves, can also join BTC
  • Trade_value: A coin's free-standing value is determined by the total amount of money it invests, and the size of the leverage can be measured by retesting the research environment.
  • Adjust_value: Contract value (USDT pricing) Adjust deviation value, too much adjustment is slower, can not be less than 20, otherwise it will not reach the minimum transaction
  • Ice_value: Iceberg assigned value, also cannot be less than 20, the smaller one from the actual selector Adjust_value/Ice_value
  • Reset: Reset the historical data

Strategic risks

Note that if a coin goes out of the independent market, for example, if it rises several times relative to the index, it will accumulate a large number of empty positions on the currency, and the same large decline will also make the strategy do a lot more.


//向上偏离最大的币的索引
var highIndex=0;
//向下偏离最大的币的索引
var lowIndex=0;

var trade_symbols = Trade_symbols.split(',')
var symbols = trade_symbols
var index = 1 //指数
if(trade_symbols.indexOf('BTC')<0){
    symbols = trade_symbols.concat(['BTC'])
}
var update_profit_time = 0
var assets = {}
var trade_info = {}
var exchange_info = HttpQuery('https://fapi.binance.com/fapi/v1/exchangeInfo')
if(!exchange_info){
    Log('无法连接网络')
    return
}
exchange_info = JSON.parse(exchange_info)
for (var i=0; i<exchange_info.symbols.length; i++){
    if(symbols.indexOf(exchange_info.symbols[i].baseAsset) > -1){
       assets[exchange_info.symbols[i].baseAsset] = {amount:0, hold_price:0, value:0, bid_price:0, ask_price:0, 
                                                     btc_price:0, btc_change:1,btc_diff:0,
                                                     realised_profit:0, margin:0, unrealised_profit:0}
       trade_info[exchange_info.symbols[i].baseAsset] = {minQty:parseFloat(exchange_info.symbols[i].filters[1].minQty),
                                                         priceSize:parseInt((Math.log10(1.1/parseFloat(exchange_info.symbols[i].filters[0].tickSize)))),
                                                         amountSize:parseInt((Math.log10(1.1/parseFloat(exchange_info.symbols[i].filters[1].stepSize))))
                                                        }
    }
}
assets.USDT = {unrealised_profit:0, margin:0, margin_balance:0, total_balance:0, leverage:0, update_time:0}

function updateAccount(){ //更新账户和持仓
    var account = exchange.GetAccount()
    var pos = exchange.GetPosition()
    if (account == null || pos == null ){
        Log('update account time out')
        return
    }
    assets.USDT.update_time = Date.now()
    for(var i=0; i<trade_symbols.length; i++){
        assets[trade_symbols[i]].margin = 0
        assets[trade_symbols[i]].unrealised_profit = 0
        assets[trade_symbols[i]].hold_price = 0
        assets[trade_symbols[i]].amount = 0
        assets[trade_symbols[i]].unrealised_profit = 0
    } 
    for(var j=0; j<account.Info.positions.length; j++){
        var pair = account.Info.positions[j].symbol 
        var coin = pair.slice(0,pair.length-4)
        if(symbols.indexOf(coin) < 0){continue}
        assets[coin].margin = parseFloat(account.Info.positions[j].initialMargin) + parseFloat(account.Info.positions[j].maintMargin)
        assets[coin].unrealised_profit = parseFloat(account.Info.positions[j].unrealizedProfit)
    }
    assets.USDT.margin = _N(parseFloat(account.Info.totalInitialMargin) + parseFloat(account.Info.totalMaintMargin),2)
    assets.USDT.margin_balance = _N(parseFloat(account.Info.totalMarginBalance),2)
    assets.USDT.total_balance = _N(parseFloat(account.Info.totalWalletBalance),2)
    assets.USDT.unrealised_profit = _N(parseFloat(account.Info.totalUnrealizedProfit),2)
    assets.USDT.leverage = _N(assets.USDT.margin/assets.USDT.total_balance,2)
    
    if(pos.length > 0){
        pos = JSON.parse(exchange.GetRawJSON())
        for(var k=0; k<pos.length; k++){
            var pair = pos[k].symbol
            var coin = pair.slice(0,pair.length-4)
            if(symbols.indexOf(coin) < 0){continue}
            assets[coin].hold_price = parseFloat(pos[k].entryPrice)
            assets[coin].amount = parseFloat(pos[k].positionAmt)
            assets[coin].unrealised_profit = parseFloat(pos[k].unRealizedProfit)
        }
    }
}

function updateIndex(){ //更新指数
    var init_prices = {}
    if(!_G('init_prices') || Reset){
        for(var i=0; i<trade_symbols.length; i++){
            init_prices[trade_symbols[i]] = (assets[trade_symbols[i]].ask_price+assets[trade_symbols[i]].bid_price)/(assets.BTC.ask_price+assets.BTC.bid_price)
        }
        Log('保存启动时的价格')
        _G('init_prices',init_prices)
    }else{
        init_prices = _G('init_prices')
        var temp = 0
        
        highIndex=0;
        lowIndex=0;
        var highChange;var lowChange;
        //本次计算找出最大偏离的高低分
        for(var i=0; i<trade_symbols.length; i++){
            assets[trade_symbols[i]].btc_price =  (assets[trade_symbols[i]].ask_price+assets[trade_symbols[i]].bid_price)/(assets.BTC.ask_price+assets.BTC.bid_price)
            if(!init_prices[trade_symbols[i]]){
                Log('添加新的币种',trade_symbols[i])
                init_prices[trade_symbols[i]] = assets[trade_symbols[i]].btc_price 
                _G('init_prices',init_prices)
            }
            assets[trade_symbols[i]].btc_change = _N(assets[trade_symbols[i]].btc_price/init_prices[trade_symbols[i]],4)
            if(i==0){
                highChange=assets[trade_symbols[i]].btc_change;
                lowChange=assets[trade_symbols[i]].btc_change;
            }
            
            if(highChange<assets[trade_symbols[i]].btc_change){
                highChange=assets[trade_symbols[i]].btc_change;
                highIndex=i;
            }
            if(lowChange>assets[trade_symbols[i]].btc_change){
                lowChange=assets[trade_symbols[i]].btc_change;
                lowIndex=i;
            }
        }
        
        for(var i=0; i<trade_symbols.length; i++){
            assets[trade_symbols[i]].btc_price =  (assets[trade_symbols[i]].ask_price+assets[trade_symbols[i]].bid_price)/(assets.BTC.ask_price+assets.BTC.bid_price)
            assets[trade_symbols[i]].btc_change = _N(assets[trade_symbols[i]].btc_price/init_prices[trade_symbols[i]],4)
            if(i!=lowIndex&&i!=highIndex){ //去掉高低分的影响
                temp += assets[trade_symbols[i]].btc_change
            }
        }
        //因为去掉了最高最低分,所以减2
        index = _N(temp/(trade_symbols.length-2), 4)
    }
    
}

function updateTick(){ //更新行情
    var ticker = HttpQuery('https://fapi.binance.com/fapi/v1/ticker/bookTicker')
    try {
        ticker = JSON.parse(ticker)
    }catch(e){
        Log('get ticker time out')
        return
    }
    for(var i=0; i<ticker.length; i++){
        var pair = ticker[i].symbol 
        var coin = pair.slice(0,pair.length-4)
        if(symbols.indexOf(coin) < 0){continue}
        assets[coin].ask_price = parseFloat(ticker[i].askPrice)
        assets[coin].bid_price = parseFloat(ticker[i].bidPrice)
        assets[coin].ask_value = _N(assets[coin].amount*assets[coin].ask_price, 2)
        assets[coin].bid_value = _N(assets[coin].amount*assets[coin].bid_price, 2)
    }
    updateIndex()
    for(var i=0; i<trade_symbols.length; i++){
        assets[trade_symbols[i]].btc_diff = _N(assets[trade_symbols[i]].btc_change - index, 4)
    }
}

function trade(symbol, dirction, value){ //交易
    if(Date.now()-assets.USDT.update_time > 10*1000){
        Log('更新账户延时,不交易')
        return
    }
    var price = dirction == 'sell' ? assets[symbol].bid_price : assets[symbol].ask_price
    var amount = _N(Math.min(value,Ice_value)/price, trade_info[symbol].amountSize)
    if(amount <= trade_info[symbol].minQty){
        Log(symbol, '合约价值偏离或冰山委托订单的大小设置过小,达不到最小成交, 至少需要: ', _N(trade_info[symbol].minQty*price,0))
        return
    }
    exchange.IO("currency", symbol+'_'+'USDT')
    exchange.SetContractType('swap')
    exchange.SetDirection(dirction)
    var f = dirction == 'buy' ? 'Buy' : 'Sell'
    var id = exchange[f](price, amount, symbol)
    if(id){
        exchange.CancelOrder(id) //订单会立即撤销
    }
}

function updateStatus(){ //状态栏信息
        var table = {type: 'table', title: '交易对信息更新', 
             cols: ['Symbol', 'amount', 'hold_price',  'price', 'diff', 'value', 'margin', 'unrealised_profit'],
             rows: []}
        var infoList;
    for (var i=0; i<symbols.length; i++){
        var price = _N((assets[symbols[i]].ask_price + assets[symbols[i]].bid_price)/2, trade_info[symbols[i]].priceSize)
        var value = _N((assets[symbols[i]].ask_value + assets[symbols[i]].bid_value)/2, 2)
        if(i==lowIndex){
           infoList = [symbols[i]+"Low", assets[symbols[i]].amount, assets[symbols[i]].hold_price, price, assets[symbols[i]].btc_diff, value, _N(assets[symbols[i]].margin,3), _N(assets[symbols[i]].unrealised_profit,3)]    
        }else if(i==highIndex){
           infoList = [symbols[i]+"High", assets[symbols[i]].amount, assets[symbols[i]].hold_price, price, assets[symbols[i]].btc_diff, value, _N(assets[symbols[i]].margin,3), _N(assets[symbols[i]].unrealised_profit,3)]
        }else{
           infoList = [symbols[i], assets[symbols[i]].amount, assets[symbols[i]].hold_price, price, assets[symbols[i]].btc_diff, value, _N(assets[symbols[i]].margin,3), _N(assets[symbols[i]].unrealised_profit,3)]
        }
        table.rows.push(infoList)
    }
    var logString = _D() + '   ' + JSON.stringify(assets.USDT) + ' Index:' + index + '\n'
    LogStatus(logString + '`' + JSON.stringify(table) + '`')
    
    if(Date.now()-update_profit_time > Log_profit_interval*1000){
        LogProfit(_N(assets.USDT.margin_balance,3))
        update_profit_time = Date.now()
    }
    
}

function onTick(){ //策略逻辑部分
    for(var i=0; i<trade_symbols.length; i++){
        var symbol = trade_symbols[i]
        if(assets[symbol].ask_price == 0){ continue }
        var aim_value = -Trade_value * _N(assets[symbol].btc_diff/0.01,1)
        
        if(i!=lowIndex&&i!=highIndex){ //高低分的货币不交易
           if(aim_value - assets[symbol].ask_value > Adjust_value&&assets[symbol].ask_value<Max_amount){
              trade(symbol,'buy', aim_value - assets[symbol].ask_value)
           }
           if(aim_value - assets[symbol].bid_value < -Adjust_value&&assets[symbol].bid_value<Max_amount){
              trade(symbol,'sell', -(aim_value - assets[symbol].bid_value))
           }
        }
    }
}

function main() {
    while(true){
        updateAccount()
        updateTick()
        onTick()
        updateStatus()
        Sleep(Interval*1000)
    }
}

Related

More

qq813380629How much leverage is this generally suitable for and how much money can be used?

Quantification of district classesis the maximum holding value of a single currency

Light cloudsHello, I have a question for you. Max_amount This refers to the maximum holding value or maximum collateral amount for each trading pair? Thank you.