리소스 로딩... 로딩...

다중 거래소 집합시장/예약 전략 예제

저자:발명가들의 수량화 - 작은 꿈, 날짜: 2018-11-10 12:20:11
태그:연구무역 지원

img


// 参数,可设置到界面。
var Interval = 100
var TickerInterval = 1000
var RecordsInterval = 1000

// 全局变量
var Amount = 0.1

function CreateExchanges(){
    var exs = {
        // 交易所对象
        ex_objs : [],

        // exs 的属性
        table : null,
        tickerInterval : 0,
        recordsInterval : 0,
        runCount : 0, 
    }
    // 初始化
    exs.tickerInterval = TickerInterval
    exs.recordsInterval = RecordsInterval

    var funcDict = {
        "GetTicker" : ["routine_ticker", "ticker", "tickerPreTime"],
        "GetRecords" : ["routine_records", "records", "recordsPreTime"],
        "Trade" : ["routine_trade", "trade", "tradePreTime"],                   // 可扩展挂单,多线程发单等功能
    }

    // 初始化
    var timeStamp = new Date().getTime()
    for(var i = 0 ; i < exchanges.length ; i++){
        var obj = {
            name : exchanges[i].GetName(),
            currency : exchanges[i].GetCurrency(),
            index : i,
            routine_ticker : null,
            ticker : null,
            tickerPre : null,
            tickerPreTime : timeStamp,
            routine_trade : null,
            trade : null,
            tradePreTime : timeStamp,
            routine_records : null,
            records : null,
            recordsPre : null,
            recordsPreTime : timeStamp,
            recordsPreBarTime : 0,
            rows : null,

        }
        // 设置代理
        exchanges[i].SetProxy(StrProxy)
        
        exs.ex_objs.push(obj)
    }

    exs.Go = function(func, interval){
        var self = this
        if(typeof(func) == "undefined"){
            throw "error, no param func"
        }

        _.each(self.ex_objs, function(obj){
            if(typeof(obj[funcDict[func][1]]) !== "undefined"){
                obj[funcDict[func][0]] = exchanges[obj.index].Go(func)
                obj[funcDict[func][2]] = new Date().getTime()
            }
        })

        Sleep(interval)
        
        _.each(self.ex_objs, function(obj){
            obj[funcDict[func][1]] = obj[funcDict[func][0]].wait(10)
        })
    }

    exs.TableUpdate = function(){
        var self = this

        self.table = {
            type : "table", 
            title : "交易所行情", 
            cols : ["名称", "交易对", "卖一价", "买一价", "最新成交价", "操作A", "操作B", "最近一次请求耗时"], 
            rows : [],
        }

        _.each(self.ex_objs, function(obj){
            var ticker = obj.ticker
            if(typeof(ticker) == "undefined" || !ticker){
                ticker = obj.tickerPre ? obj.tickerPre : {Buy : "Nan", Sell : "Nan", Last : "Nan", High : "Nan", Low : "Nan"}
            }
            self.table.rows.push([
                obj.name, 
                obj.currency, 
                ticker.Sell, 
                ticker.Buy, 
                ticker.Last, 
                {
                    'type': 'button',
                    'cmd': "LogStatus" + "_" + obj.index + "_" + "Buy",                              
                    'name': '买入'
                },
                {
                    'type': 'button',
                    'cmd': "LogStatus" + "_" + obj.index + "_" + "Sell",    
                    'class': 'btn btn-xs btn-danger',                          
                    'name': '卖出'
                }, 
                (new Date().getTime() - obj.tickerPreTime),
            ])
        })
        
        self.runCount++
        LogStatus("时间:", _D(), "运行次数:", self.runCount, " ", "\n", '`' + JSON.stringify(self.table) + '`')
    }   

    exs.Chart = function(chartObj, chartCfg){
        var self = this

        _.each(self.ex_objs, function(obj){
            if(typeof(obj.records) !== "undefined" && obj.records){
                if(obj.recordsPreBarTime == 0){                            // 初始化
                    for(var i = 0; i < obj.records.length; i++){
                        chartObj.add(obj.index, [obj.records[i].Time, obj.records[i].Open, obj.records[i].High, obj.records[i].Low, obj.records[i].Close])
                    }
                    obj.recordsPreBarTime = obj.records[obj.records.length - 1].Time
                } else {
                    if(obj.records[obj.records.length - 1].Time !== obj.recordsPreBarTime){
                        chartObj.add(obj.index, [obj.records[obj.records.length - 1].Time, obj.records[obj.records.length - 1].Open, obj.records[obj.records.length - 1].High, obj.records[obj.records.length - 1].Low, obj.records[obj.records.length - 1].Close])
                        obj.recordsPreBarTime = obj.records[obj.records.length - 1].Time
                    } else {
                        chartObj.add(obj.index, [obj.records[obj.records.length - 1].Time, obj.records[obj.records.length - 1].Open, obj.records[obj.records.length - 1].High, obj.records[obj.records.length - 1].Low, obj.records[obj.records.length - 1].Close], -1)
                    }
                }
            }
        })
        chartObj.update(chartCfg)
    } 

    exs.Trade = function(){

    }

    exs.GetTicker = function(){
        var self = this
        self.Go("GetTicker", self.tickerInterval)
        _.each(self.ex_objs, function(obj){
            if(typeof(obj.ticker) !== "undefined" && obj.ticker){
                obj.tickerPre = obj.ticker
            }
        })
    }

    exs.GetRecords = function(){
        var self = this
        self.Go("GetRecords", self.recordsInterval)
        _.each(self.ex_objs, function(obj){
            if(typeof(obj.records) !== "undefined" && obj.records){
                obj.recordsPre = obj.records
            }
        })
    }


    return exs
}

function main(){
    // 初始化 交易所集合对象
    var exs = CreateExchanges()

    // 图表初始化
    var arrCfg = []
    for(var i = 0 ; i < exchanges.length ; i++){
        var cfg = {
            title: {
                text: exchanges[i].GetName() + "-" + exchanges[i].GetCurrency()
            },
            xAxis: {
                type: 'datetime'
            },
            series: [{
                type: 'candlestick',
                name: 'K线',
                id: "" + i,
                data: [] 
            }]
        }
        arrCfg.push(cfg)
    }
    var chart = Chart(arrCfg)
    chart.reset()

    while(true){
        // 处理交互
        var cmd = GetCommand()
        if(cmd){
            Log("cmd:", cmd)  // 测试
            
            var arr = cmd.split("_")
            if(arr.length == 3){
                var idx = parseInt(arr[1])
                var type = arr[2]
                if(type == "Buy"){
                    $.Buy(exchanges[idx], Amount)
                } else if(type == "Sell"){
                    $.Sell(exchanges[idx], Amount)
                } else {
                    Log("错误的 命令,type:", type, "#FF0000")    
                }
            } else if(arr.length == 1) {
                var amount = arr[0].split(":")[1]
                Amount = parseInt(amount)
            }else {
                Log("错误的 命令", "#FF0000")
            }
        }
        
        // 获取 records 数据
        exs.GetRecords()
        // 获取 ticker 数据
        exs.GetTicker()

        // 处理界面
        exs.TableUpdate()
        exs.Chart(chart, arrCfg)

        Sleep(Interval)
    }
}

관련

더 많은