├── .gitignore ├── main.js ├── README.md ├── algorithm_interface.js ├── algorithms ├── follow_mercadobitcoin.algo ├── follow_bitstamp.algo ├── smart_order.algo └── market_maker.algo ├── algorithm_application.js └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea/ 3 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | var sys = require('sys'); 2 | var WebSocketClient = require('websocket').client; 3 | 4 | var wsClient = new WebSocketClient(); 5 | wsClient.connect('wss://api.testnet.blinktrade.com/trade/'); 6 | 7 | wsClient.addListener('connect', function(ws) { 8 | ws.addListener('message', function(buf) { 9 | sys.debug('Got data: ' + sys.inspect(buf)); 10 | }); 11 | ws.onmessage = function(m) { 12 | sys.debug('Got message: ' + m); 13 | } 14 | ws.send('{"MsgType":"1", "TestReqID":0}'); 15 | }); 16 | 17 | 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### algorithm-trading ( DOCUMENTATION IS INCOMPLETE, TAKE A LOOK AT THE [EXAMPLES](https://github.com/blinktrade/algorithm-trading/tree/master/algorithms) ) 2 | 3 | 4 | This repository contains algorithm trading programs ( AKA trading strategies, trading bot ) which are compatible with all exchanges running the blinktrade platform. Those algorithms are executed in the users browser context and not in the servers. 5 | 6 | ### Pre-requisites to create your own algorithm trading 7 | - Basic knowledge of JavaScript 8 | - Curiosity 9 | 10 | ### Is there a test environment to test my algorithms? 11 | - Yes, [blinktrade tesnet exchange](https://testnet.blinktrade.com/) 12 | 13 | 14 | ### List of blinktrade approved algorithm trading strategies 15 | - [market_maker.algo ** incomplete **](https://github.com/blinktrade/algorithm-trading/blob/master/algorithms/market_maker.algo) 16 | 17 | 18 | ### Basic structure of an algorithm 19 | ```JavaScript 20 | -----BEGIN ALGO DEFINITION----- 21 | { 22 | "id": "any_id_here", 23 | "description": "Description of what your algorithm does", 24 | "params": [ 25 | {"name":"your_parameter_1", "label":"Your Parammeter #1", "type":"text", "value":"0", "validator":"required; validateNumber; validateMin 10; validateMax 1000;" }, 26 | {"name":"your_parameter_2", "label":"Your Parammeter #2", "type":"text", "value":"5", "validator":"required; validateInteger; validateMin 1; validateMax 5;" } 27 | ], 28 | "creator": "name_of_the_function_which_the_exchange_will_invoke_to_create_an_instance_of_your_algo", 29 | "destructor": "name_of_the_functions_which_the_exchange_will_invoke_when_destroying_the_instance_of_your_algo", 30 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 31 | } 32 | -----END ALGO DEFINITION----- 33 | -----BEGIN ALGO----- 34 | // define a class that implements the following interface [interface](https://github.com/blinktrade/algorithm-trading/blob/master/algorithm_interface.js) here 35 | 36 | function name_of_the_function_which_the_exchange_will_invoke_to_create_an_instance_of_your_algo() { 37 | return new MyAlgo(); 38 | } 39 | 40 | function name_of_the_functions_which_the_exchange_will_invoke_when_destroying_the_instance_of_your_algo(instance_of_my_algo) { 41 | delete instance_of_my_algo; 42 | } 43 | -----END ALGO----- 44 | ``` 45 | 46 | ### How does it work 47 | The exchange expects you to create a javascript class that implements the following [interface](https://github.com/blinktrade/algorithm-trading/blob/master/algorithm_interface.js) 48 | 49 | 50 | 51 | ### List of exchanges running blinktrade platform 52 | - [chilebit](https://chilebit.net) 53 | - [foxbit](https://foxbit.com.br) 54 | - [VBTC](https://vbtc.vn) 55 | - [surbitcoin](https://surbitcoin.com) 56 | - [urdubit](https://urdubit.com) 57 | -------------------------------------------------------------------------------- /algorithm_interface.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @param {Application} application 4 | * @param {string} symbol 5 | * @constructor 6 | */ 7 | var AlgorithmTradingInterface = function(application, symbol){}; 8 | 9 | /** 10 | * @enum {string} Balance Types 11 | */ 12 | AlgorithmTradingInterface.BalanceType = { 13 | DEPOSIT : 'deposit', 14 | LOCKED: 'locked', 15 | AVAILABLE: 'available' 16 | }; 17 | 18 | /** 19 | * Invoked when your algorithm is ready to run. 20 | * Don't try to send orders before the start method. 21 | * @param {Object.} params 22 | */ 23 | AlgorithmTradingInterface.prototype.start = function(params) { }; 24 | 25 | /** 26 | * Invoked before the system stops your algo. Do your cleanup here 27 | */ 28 | AlgorithmTradingInterface.prototype.stop = function() { }; 29 | 30 | 31 | /** 32 | * Invoked whenever your balance change 33 | * @param {string} currency 34 | * @param {number} balance 35 | * @param {AlgorithmTradingInterface.BalanceType} balance_type 36 | */ 37 | AlgorithmTradingInterface.prototype.onBalanceUpdate = function(currency, balance, balance_type) { }; 38 | 39 | 40 | /** 41 | * Invoked when you update your parameters. 42 | * @param {Object.} params 43 | */ 44 | AlgorithmTradingInterface.prototype.onUpdateParams = function(params) { }; 45 | 46 | 47 | /** 48 | * Invoked to report the arrival of a new order, and executions on it. 49 | * @param {Object.} msg 50 | * @see {http://btobits.com/fixopaedia/fixdic44/message_Execution_Report_8_.html} 51 | */ 52 | AlgorithmTradingInterface.prototype.onExecutionReport = function(msg) { }; 53 | 54 | 55 | /** 56 | * Invoked when there was a change in the order book 57 | * @param {Array.>} order_book 58 | */ 59 | AlgorithmTradingInterface.prototype.onOrderBookChange = function(order_book) { }; 60 | 61 | 62 | /** 63 | * Invoked when there is a change in the ticker 64 | * @param {Object.} msg 65 | */ 66 | AlgorithmTradingInterface.prototype.onTicker = function(msg) { }; 67 | 68 | 69 | /** 70 | * Invoked when a new order arrives in the order book 71 | * @param {Object.} msg 72 | */ 73 | AlgorithmTradingInterface.prototype.onOrderBookNewOrder = function(msg) { }; 74 | 75 | 76 | /** 77 | * Invoked when an order gets updated in the order book 78 | * @param {Object.} msg 79 | */ 80 | AlgorithmTradingInterface.prototype.onOrderBookUpdateOrder = function(msg) { }; 81 | 82 | 83 | /** 84 | * Invoked when an order gets deleted from the order book 85 | * @param {Object.} msg 86 | */ 87 | AlgorithmTradingInterface.prototype.onOrderBookDeleteOrder = function(msg) { }; 88 | 89 | 90 | /** 91 | * Invoked when one or more orders gets deleted from the order book 92 | * @param {Object.} msg 93 | */ 94 | AlgorithmTradingInterface.prototype.onOrderBookDeleteOrdersThru = function(msg) { }; 95 | 96 | 97 | /** 98 | * Invoked when there is a new trade in the exchange 99 | * @param {Object.} msg 100 | */ 101 | AlgorithmTradingInterface.prototype.onTrade = function(msg) { }; -------------------------------------------------------------------------------- /algorithms/follow_mercadobitcoin.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "bitstamp", 5 | "description": "Notifies the user when there is a new best bid/ask at MercadoBitcoin", 6 | "params": [], 7 | "creator": "blinktrade.FollowMercadoBitcoin.create", 8 | "destructor": "blinktrade.FollowMercadoBitcoin.destroy", 9 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 10 | } 11 | -----END ALGO DEFINITION----- 12 | -----BEGIN ALGO----- 13 | /**/ 14 | 15 | 16 | /** 17 | * Namespace. 18 | */ 19 | var blinktrade = {}; 20 | 21 | /** 22 | * Workaround using yahoo yql api to make cross domain requests 23 | * @param {string} url 24 | * @param {function(*)} fn 25 | * @param {Object} selfObj 26 | */ 27 | function crossDomainRequest( url, fn, selfObj) { 28 | var callback_function_name = 'yqlCallback' + parseInt(Math.random() * 1000000, 10); 29 | self[callback_function_name] = function( yqlResult ) { 30 | goog.bind(fn,selfObj, yqlResult.query.results)(); 31 | }; 32 | 33 | var yql = 'select * from json where url="' + url + '"'; 34 | var uri = 'https://query.yahooapis.com/v1/public/yql?q=' + 35 | encodeURIComponent(yql) + '&format=json&callback=' + callback_function_name ; 36 | importScripts(uri); 37 | } 38 | 39 | /** 40 | * @param {Object} application 41 | * @param {string} symbol 42 | * @constructor 43 | */ 44 | blinktrade.FollowMercadoBitcoin = function(application, symbol){ 45 | this.application_ = application; 46 | this.symbol_ = symbol; 47 | global_instance = this; 48 | 49 | }; 50 | 51 | /** 52 | * @type {number} 53 | */ 54 | blinktrade.FollowMercadoBitcoin.prototype.last_best_bid_; 55 | 56 | /** 57 | * @type {number} 58 | */ 59 | blinktrade.FollowMercadoBitcoin.prototype.last_best_ask_; 60 | 61 | /** 62 | * @param {Application} application 63 | * @param {string} symbol 64 | * @return {blinktrade.FollowMercadoBitcoin} 65 | */ 66 | blinktrade.FollowMercadoBitcoin.create = function(application,symbol) { 67 | return new blinktrade.FollowMercadoBitcoin(application,symbol); 68 | }; 69 | 70 | /** 71 | * @param {Object} params 72 | */ 73 | blinktrade.FollowMercadoBitcoin.prototype.start = function(params) { 74 | console.log('blinktrade.FollowMercadoBitcoin.prototype.start'); 75 | this.timer_ = setInterval(goog.bind(crossDomainRequest, 76 | this, 77 | 'https://www.mercadobitcoin.net/api/v2/ticker/', 78 | this.onMBCallBack_, 79 | this ), 6000 ); // every 60 seconds 80 | }; 81 | 82 | 83 | blinktrade.FollowMercadoBitcoin.prototype.stop = function() { 84 | clearInterval(this.timer_); 85 | }; 86 | 87 | /** 88 | * @param {Object.} params 89 | */ 90 | blinktrade.FollowMercadoBitcoin.prototype.onUpdateParams = function(params) {}; 91 | 92 | 93 | 94 | blinktrade.FollowMercadoBitcoin.prototype.onMBCallBack_ = function(ticker){ 95 | var best_bid = parseFloat(ticker['ticker']['buy']); 96 | var best_ask = parseFloat(ticker['ticker']['sell']); 97 | 98 | if (this.last_best_bid_ != best_bid) { 99 | this.last_best_bid_ = best_bid; 100 | this.application_.showNotification('MercadoBitcoin', 'The new best bid is ' + best_bid, 'success' ); 101 | } 102 | 103 | if ( this.last_best_ask_ != best_ask ) { 104 | this.last_best_ask_ = best_ask; 105 | this.application_.showNotification('MercadoBitcoin', 'The new best ask is ' + best_ask, 'info' ); 106 | } 107 | }; 108 | 109 | //-----END ALGO----- 110 | -------------------------------------------------------------------------------- /algorithms/follow_bitstamp.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "bitstamp", 5 | "description": "Notifies the user when there is a new best bid/ask and trade at BitStamp", 6 | "params": [ 7 | {"name":"exchange_rate", "label":"Dollar exchange rate", "type":"text", "value":"1", "validator":"required; validateNumber; validateMin 0;" } 8 | ], 9 | "creator": "blinktrade.FollowBitStampAlgo.create", 10 | "destructor": "blinktrade.FollowBitStampAlgo.destroy", 11 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 12 | } 13 | -----END ALGO DEFINITION----- 14 | -----BEGIN ALGO----- 15 | /**/ 16 | 17 | 18 | /** 19 | * Namespace. 20 | */ 21 | var blinktrade = {}; 22 | 23 | 24 | /** 25 | * @param {Object} application 26 | * @param {string} symbol 27 | * @constructor 28 | */ 29 | blinktrade.FollowBitStampAlgo = function(application, symbol){ 30 | this.application_ = application; 31 | this.symbol_ = symbol; 32 | this.bitstamp_order_book_channel_subscription_ = false; 33 | }; 34 | 35 | /** 36 | * @type {boolean} 37 | */ 38 | blinktrade.FollowBitStampAlgo.prototype.bitstamp_order_book_channel_subscription_; 39 | 40 | /** 41 | * @type {number} 42 | */ 43 | blinktrade.FollowBitStampAlgo.prototype.last_best_bid_; 44 | 45 | /** 46 | * @type {number} 47 | */ 48 | blinktrade.FollowBitStampAlgo.prototype.last_best_ask_; 49 | 50 | 51 | /** 52 | * @param {Application} application 53 | * @param {string} symbol 54 | * @return {blinktrade.FollowBitStampAlgo} 55 | */ 56 | blinktrade.FollowBitStampAlgo.create = function(application,symbol) { 57 | return new blinktrade.FollowBitStampAlgo(application,symbol); 58 | }; 59 | 60 | /** 61 | * @param {Object} params 62 | */ 63 | blinktrade.FollowBitStampAlgo.prototype.start = function(params) { 64 | this.ws_pusher_ = new WebSocket('wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?protocol=7&client=js&version=2.1.6&flash=false'); 65 | this.ws_pusher_.onopen = goog.bind(this.onPusherOpen_, this); 66 | this.ws_pusher_.onmessage = goog.bind(this.onPusherMessage_, this); 67 | this.ws_pusher_.onclose = goog.bind(this.onPusherClose_, this); 68 | }; 69 | 70 | blinktrade.FollowBitStampAlgo.prototype.onPusherOpen_ = function() { 71 | this.ws_pusher_.send( JSON.stringify({"event":"pusher:subscribe","data":{"channel":"order_book"}})); 72 | this.ws_pusher_.send( JSON.stringify({"event":"pusher:subscribe","data":{"channel":"live_trades"}})); 73 | }; 74 | 75 | blinktrade.FollowBitStampAlgo.prototype.onPusherClose_ = function() { 76 | this.application_.stop('Problems with pusher'); 77 | }; 78 | 79 | blinktrade.FollowBitStampAlgo.prototype.onPusherMessage_ = function (e) { 80 | var msg = JSON.parse(e.data); 81 | switch(msg["event"]) { 82 | case 'pusher:error': 83 | this.stop( msg["data"]["message"] ); 84 | break; 85 | case 'pusher_internal:subscription_succeeded': 86 | if (msg["channel"] == "order_book") { 87 | this.bitstamp_order_book_channel_subscription_ = true; 88 | } 89 | break; 90 | case 'data': 91 | switch(msg["channel"]){ 92 | case "order_book": 93 | this.onBitStampOrderBookData(JSON.parse(msg["data"])); 94 | return; 95 | case "live_trades": 96 | this.onBitStampTrade(JSON.parse(msg["data"])); 97 | return; 98 | } 99 | } 100 | }; 101 | 102 | /** 103 | * @param {Object} trade 104 | */ 105 | blinktrade.FollowBitStampAlgo.prototype.onBitStampTrade = function(trade) { 106 | var exchange_rate = parseFloat(this.application_.getParameters()['exchange_rate']); 107 | this.application_.showNotification('BitStamp trade', 108 | 'price:' + parseFloat(trade['price']) * exchange_rate + ', amount:' + trade['amount'], 'error' ); 109 | }; 110 | 111 | /** 112 | * @param {Object.>> } order_book 113 | */ 114 | blinktrade.FollowBitStampAlgo.prototype.onBitStampOrderBookData = function(order_book) { 115 | var exchange_rate = parseFloat(this.application_.getParameters()['exchange_rate']); 116 | 117 | var best_bid = parseFloat(order_book['bids'][0][0]) * exchange_rate; 118 | var best_ask = parseFloat(order_book['asks'][0][0]) * exchange_rate; 119 | 120 | if (this.last_best_bid_ != best_bid) { 121 | this.last_best_bid_ = best_bid; 122 | this.application_.showNotification('BitStamp', 'The new best bid is ' + best_bid, 'success' ); 123 | } 124 | 125 | 126 | if ( this.last_best_ask_ != best_ask ) { 127 | this.last_best_ask_ = best_ask; 128 | this.application_.showNotification('BitStamp', 'The new best ask is ' + best_ask, 'info' ); 129 | } 130 | }; 131 | 132 | blinktrade.FollowBitStampAlgo.prototype.stop = function() { 133 | this.ws_pusher_.close(); 134 | }; 135 | 136 | //-----END ALGO----- 137 | -------------------------------------------------------------------------------- /algorithms/smart_order.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "blinktrade", 5 | "description": "Make sure your order is always on top", 6 | "params": [ 7 | {"name":"side", "label":"Buy(1) / Sell(2)", "type":"number", "value":"1", "filter":"positive_number", "validator":"required; validateMin 1; validateMax 2; validateNumber;" }, 8 | {"name":"qty", "label":"Qty", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" }, 9 | {"name":"min_price", "label":"Minimum Price", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" }, 10 | {"name":"max_price", "label":"Maximum Price", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" } 11 | ], 12 | "creator": "blinktrade.SmartOrderAlgo.create", 13 | "destructor": "blinktrade.SmartOrderAlgo.destroy", 14 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"], 15 | "tickers" : ["UOL:USDBRT","BITFINEX:BTCUSD", "OKCOIN:BTCCNY"] 16 | } 17 | -----END ALGO DEFINITION----- 18 | -----BEGIN ALGO----- 19 | /**/ 20 | 21 | /** 22 | * Namespace. 23 | */ 24 | var blinktrade = {}; 25 | 26 | /** 27 | * @param {Object} application 28 | * @param {string} symbol 29 | * @constructor 30 | */ 31 | blinktrade.SmartOrderAlgo = function(application, symbol){ 32 | this.application_ = application; 33 | this.symbol_ = symbol; 34 | 35 | this.my_orders_prefix_ = 'p' + parseInt( 1e4 * Math.random() , 10 ) + '_'; 36 | this.price_increment_ = 0.01; 37 | }; 38 | 39 | /** 40 | * @type {Object} 41 | */ 42 | blinktrade.SmartOrderAlgo.prototype.current_order_; 43 | 44 | 45 | /** 46 | * @type {number} 47 | */ 48 | blinktrade.SmartOrderAlgo.prototype.target_price_; 49 | 50 | 51 | /** 52 | * @param {Application} application 53 | * @param {string} symbol 54 | * @return {blinktrade.SmartOrderAlgo} 55 | */ 56 | blinktrade.SmartOrderAlgo.create = function(application,symbol) { 57 | return new blinktrade.SmartOrderAlgo(application,symbol); 58 | }; 59 | 60 | /** 61 | * @param {Object} params 62 | */ 63 | blinktrade.SmartOrderAlgo.prototype.start = function(params) { 64 | this.target_qty_ = params['qty'] * 1e8; 65 | 66 | this.cancellAlgoOrders(); 67 | this.sendOrders(); 68 | 69 | this.timer_ = setInterval(goog.bind(this.sendOrders, this), 1000 ); // every 1 second 70 | }; 71 | 72 | blinktrade.SmartOrderAlgo.prototype.stop = function() { 73 | clearInterval(this.timer_); 74 | this.cancellAlgoOrders(); 75 | }; 76 | 77 | /** 78 | * @param {Object} msg 79 | */ 80 | blinktrade.SmartOrderAlgo.prototype.onTicker = function(msg) { 81 | console.log(msg); 82 | }; 83 | 84 | /** 85 | * @param {Object.} params 86 | */ 87 | blinktrade.SmartOrderAlgo.prototype.onUpdateParams = function(params) { 88 | if (params['qty'] * 1e8 !== this.target_qty_) { 89 | this.target_qty_ = params['qty'] * 1e8; 90 | this.cancellAlgoOrders(); 91 | } 92 | this.sendOrders(); 93 | }; 94 | 95 | /** 96 | * 97 | * @param {Object.} msg 98 | */ 99 | blinktrade.SmartOrderAlgo.prototype.onExecutionReport = function(msg) { 100 | this.target_qty_ = msg['LeavesQty']; 101 | }; 102 | 103 | 104 | blinktrade.SmartOrderAlgo.prototype.cancellAlgoOrders = function() { 105 | if (goog.isDefAndNotNull(this.current_order_)) { 106 | this.application_.cancelOrder(this.current_order_['ClOrdID']); 107 | } 108 | this.current_order_ = null; 109 | }; 110 | 111 | 112 | blinktrade.SmartOrderAlgo.prototype.sendOrders = function() { 113 | var params = this.application_.getParameters(); 114 | var max_price = params["max_price"] * 1e8; 115 | var min_price = params["min_price"] * 1e8; 116 | 117 | if (this.target_qty_ < 10000) { // minimum qty 118 | return; 119 | } 120 | 121 | var order_book = this.application_.getOrderBook(); 122 | 123 | var best_market_price; 124 | var order_at_top_of_the_book; 125 | var counter_order_at_top_of_the_book; 126 | 127 | 128 | if (params["side"] == 1) { 129 | order_at_top_of_the_book = order_book["bids"][0]; 130 | counter_order_at_top_of_the_book = order_book["asks"][0]; 131 | } else { 132 | order_at_top_of_the_book = order_book["asks"][0]; 133 | counter_order_at_top_of_the_book = order_book["bids"][0]; 134 | } 135 | 136 | var do_i_have_the_best_order = false; 137 | if (goog.isDefAndNotNull(this.current_order_)) { 138 | do_i_have_the_best_order = (this.current_order_['Price'] == order_at_top_of_the_book[0] && 139 | this.current_order_['Qty'] == order_at_top_of_the_book[1]); 140 | } 141 | 142 | var price_better_than_the_current_order_price = order_at_top_of_the_book[0]; 143 | if (do_i_have_the_best_order) { 144 | var book_side = "bids"; 145 | if (params["side"] == 2) { 146 | book_side = "asks"; 147 | } 148 | 149 | for (var i =1; i < order_book[book_side].length; ++i ) { 150 | if ( (book_side == "bids" && order_book[book_side][i][0] < price_better_than_the_current_order_price) 151 | || (book_side == "asks" && order_book[book_side][i][0] > price_better_than_the_current_order_price) ) { 152 | price_better_than_the_current_order_price = order_book[book_side][i][0]; 153 | break; 154 | } 155 | } 156 | } 157 | 158 | 159 | if (params["side"] == 1 ) { // BUY 160 | price_better_than_the_current_order_price = 161 | price_better_than_the_current_order_price + (this.price_increment_ * 1e8); 162 | } else if (params["side"] == 2 ) { // SELL 163 | price_better_than_the_current_order_price = 164 | price_better_than_the_current_order_price - (this.price_increment_ * 1e8); 165 | } 166 | 167 | // find the target price now 168 | if (params["side"] == 1 ) { // BUY 169 | if (price_better_than_the_current_order_price <= max_price && price_better_than_the_current_order_price >= min_price ){ 170 | this.target_price_ = price_better_than_the_current_order_price; 171 | } else if (price_better_than_the_current_order_price >= max_price ) { 172 | this.target_price_ = max_price; 173 | } else { 174 | this.target_price_ = min_price; 175 | } 176 | } else { 177 | if (price_better_than_the_current_order_price <= max_price && price_better_than_the_current_order_price >= min_price ){ 178 | this.target_price_ = price_better_than_the_current_order_price; 179 | } else if (price_better_than_the_current_order_price <= min_price ) { 180 | this.target_price_ = min_price; 181 | } else { 182 | this.target_price_ = max_price; 183 | } 184 | } 185 | 186 | if (params["side"] == 1 && this.target_price_ >= counter_order_at_top_of_the_book[0] || 187 | params["side"] == 2 && this.target_price_ <= counter_order_at_top_of_the_book[0]) { 188 | return; // we don't want to cause an execution. 189 | } 190 | 191 | 192 | var should_send_new_order = false; 193 | if (goog.isDefAndNotNull(this.current_order_)) { 194 | if ((this.current_order_["Side"] != params["side"] )) { 195 | this.application_.cancelOrder(this.current_order_['ClOrdID']); 196 | should_send_new_order = true; 197 | } 198 | if (this.current_order_["Price"] !== this.target_price_ ) { 199 | this.application_.cancelOrder(this.current_order_['ClOrdID']); 200 | should_send_new_order = true; 201 | } 202 | } else { 203 | should_send_new_order = true; 204 | } 205 | 206 | if (should_send_new_order) { 207 | this.current_order_ = { 208 | 'Side' : params["side"], 209 | 'ClOrdID' : this.my_orders_prefix_ + parseInt( 1e7 * Math.random() , 10 ), 210 | 'Qty' : this.target_qty_, 211 | 'Price' : this.target_price_ 212 | }; 213 | 214 | if (this.current_order_['Side'] == 1 ) { 215 | this.application_.sendBuyLimitedOrder(this.current_order_['Qty'], 216 | this.current_order_['Price'], 217 | this.current_order_['ClOrdID']); 218 | 219 | } else { 220 | this.application_.sendSellLimitedOrder(this.current_order_['Qty'], 221 | this.current_order_['Price'], 222 | this.current_order_['ClOrdID']); 223 | } 224 | } 225 | }; 226 | 227 | 228 | 229 | //-----END ALGO----- 230 | -------------------------------------------------------------------------------- /algorithms/market_maker.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "blinktrade", 5 | "description": "Make the market following bitstamp order book", 6 | "params": [ 7 | {"name":"dollar", "label":"Dollar ex rate", "type":"number", "value":"", "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" }, 8 | {"name":"spread", "label":"Spread", "type":"number", "value":"1", "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" }, 9 | {"name":"limit", "label":"Limit", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" } 10 | ], 11 | "creator": "blinktrade.SimpleMarketMarketAlgo.create", 12 | "destructor": "blinktrade.SimpleMarketMarketAlgo.destroy", 13 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 14 | } 15 | -----END ALGO DEFINITION----- 16 | -----BEGIN ALGO----- 17 | /**/ 18 | 19 | /** 20 | * Namespace. 21 | */ 22 | var blinktrade = {}; 23 | 24 | /** 25 | * @param {Object} application 26 | * @param {string} symbol 27 | * @constructor 28 | */ 29 | blinktrade.SimpleMarketMarketAlgo = function(application, symbol){ 30 | this.application_ = application; 31 | this.symbol_ = symbol; 32 | this.bitstamp_order_book_channel_subscription_ = false; 33 | }; 34 | 35 | /** 36 | * @type {boolean} 37 | */ 38 | blinktrade.SimpleMarketMarketAlgo.prototype.bitstamp_order_book_channel_subscription_; 39 | 40 | /** 41 | * @type {number} 42 | */ 43 | blinktrade.SimpleMarketMarketAlgo.prototype.last_best_bid_; 44 | 45 | /** 46 | * @type {number} 47 | */ 48 | blinktrade.SimpleMarketMarketAlgo.prototype.last_best_ask_; 49 | 50 | 51 | 52 | /** 53 | * @param {Application} application 54 | * @param {string} symbol 55 | * @return {blinktrade.SimpleMarketMarketAlgo} 56 | */ 57 | blinktrade.SimpleMarketMarketAlgo.create = function(application,symbol) { 58 | return new blinktrade.SimpleMarketMarketAlgo(application,symbol); 59 | }; 60 | 61 | /** 62 | * @param {Object} params 63 | */ 64 | blinktrade.SimpleMarketMarketAlgo.prototype.start = function(params) { 65 | this.startPusher_(); 66 | }; 67 | 68 | blinktrade.SimpleMarketMarketAlgo.prototype.stop = function() { 69 | this.ws_pusher_.close(); 70 | this.ws_pusher_ = null; 71 | }; 72 | 73 | blinktrade.SimpleMarketMarketAlgo.prototype.startPusher_ = function() { 74 | this.ws_pusher_ = new WebSocket('wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?protocol=7&client=js&version=2.1.6&flash=false'); 75 | this.ws_pusher_.onopen = goog.bind(this.onPusherOpen_, this); 76 | this.ws_pusher_.onmessage = goog.bind(this.onPusherMessage_, this); 77 | this.ws_pusher_.onclose = goog.bind(this.onPusherClose_, this); 78 | }; 79 | 80 | blinktrade.SimpleMarketMarketAlgo.prototype.onPusherOpen_ = function() { 81 | this.ws_pusher_.send( JSON.stringify({"event":"pusher:subscribe","data":{"channel":"order_book"}})); 82 | this.ws_pusher_.send( JSON.stringify({"event":"pusher:subscribe","data":{"channel":"live_trades"}})); 83 | }; 84 | 85 | blinktrade.SimpleMarketMarketAlgo.prototype.onPusherClose_ = function() { 86 | this.startPusher_(); 87 | }; 88 | 89 | 90 | blinktrade.SimpleMarketMarketAlgo.prototype.onPusherMessage_ = function (e) { 91 | var msg = JSON.parse(e.data); 92 | switch(msg["event"]) { 93 | case 'pusher:error': 94 | this.stop( msg["data"]["message"] ); 95 | break; 96 | case 'pusher_internal:subscription_succeeded': 97 | if (msg["channel"] == "order_book") { 98 | this.bitstamp_order_book_channel_subscription_ = true; 99 | } 100 | break; 101 | case 'data': 102 | switch(msg["channel"]){ 103 | case "order_book": 104 | this.onBitStampOrderBookData(JSON.parse(msg["data"])); 105 | return; 106 | case "live_trades": 107 | this.onBitStampTrade(JSON.parse(msg["data"])); 108 | return; 109 | } 110 | } 111 | }; 112 | 113 | 114 | /** 115 | * @param {Object} trade 116 | */ 117 | blinktrade.SimpleMarketMarketAlgo.prototype.onBitStampTrade = function(trade) { 118 | var exchange_rate = this.application_.getParameters()['dollar']; 119 | }; 120 | 121 | 122 | /** 123 | * @param {Object.>> } order_book 124 | */ 125 | blinktrade.SimpleMarketMarketAlgo.prototype.onBitStampOrderBookData = function(order_book) { 126 | var exchange_rate = this.application_.getParameters()['dollar']; 127 | 128 | var best_bid = parseInt(parseFloat(order_book['bids'][0][0]) * exchange_rate * 1e8,10); 129 | var best_ask = parseInt(parseFloat(order_book['asks'][0][0]) * exchange_rate * 1e8,10); 130 | 131 | var market_has_changed = false; 132 | 133 | if (this.last_best_bid_ != best_bid) { 134 | this.last_best_bid_ = best_bid; 135 | market_has_changed = true; 136 | } 137 | 138 | 139 | if ( this.last_best_ask_ != best_ask ) { 140 | this.last_best_ask_ = best_ask; 141 | market_has_changed = true; 142 | } 143 | 144 | if (market_has_changed) { 145 | this.cancelOrdersOutsideOfLimits(); 146 | this.makeTheMarket(); 147 | } 148 | }; 149 | 150 | 151 | blinktrade.SimpleMarketMarketAlgo.prototype.calculateLimits = function() { 152 | var params = this.application_.getParameters(); 153 | var best_bid = this.last_best_bid_; 154 | var best_ask = this.last_best_ask_; 155 | var spread = params["spread"]; 156 | 157 | if (best_bid == null && best_ask == null) { 158 | this.application_.stop("No best bid/ask found."); 159 | return; 160 | } 161 | 162 | // calculate the operation limits 163 | 164 | this.min_limit_bid_price_ = null; 165 | this.max_limit_bid_price_ = null; 166 | this.min_limit_ask_price_ = null; 167 | this.max_limit_ask_price_ = null; 168 | 169 | if (best_bid != null) { 170 | this.min_limit_bid_price_ = best_bid * ( 100 - spread/2 - spread/10 )/100 ; 171 | this.max_limit_bid_price_ = best_bid * ( 100 - spread/2 )/100 ; 172 | } 173 | 174 | if (best_ask != null) { 175 | this.min_limit_ask_price_ = best_ask * ( 100 + spread/2 )/100; 176 | this.max_limit_ask_price_ = best_ask * ( 100 + spread/2 + spread/10 )/100; 177 | } 178 | 179 | return { 180 | "min_limit_bid_price": this.min_limit_bid_price_, 181 | "max_limit_bid_price": this.max_limit_bid_price_, 182 | "min_limit_ask_price": this.min_limit_ask_price_, 183 | "max_limit_ask_price": this.max_limit_ask_price_ 184 | }; 185 | }; 186 | 187 | blinktrade.SimpleMarketMarketAlgo.prototype.getMyVolume = function() { 188 | var sum_buy_volume = 0; 189 | var sum_sell_volume = 0; 190 | 191 | var my_orders = this.application_.getOpenOrders(); 192 | for (var order_id in my_orders) { 193 | var order = my_orders[order_id]; 194 | 195 | var is_an_order_sent_from_this_algo = (order['ClOrdID'].substr(0,4) == 'algo'); 196 | 197 | 198 | var volume_not_yet_executed = (order['LeavesQty'] * order['Price'] / 1e8 ); 199 | 200 | var is_buy_order = (order['Side'] == '1' ); 201 | if (is_an_order_sent_from_this_algo && is_buy_order){ 202 | sum_buy_volume += volume_not_yet_executed; 203 | } 204 | 205 | var is_sell_order = (order['Side'] == '2' ); 206 | if (is_an_order_sent_from_this_algo && is_sell_order){ 207 | sum_sell_volume += volume_not_yet_executed; 208 | } 209 | } 210 | return [ sum_buy_volume, sum_sell_volume]; 211 | }; 212 | 213 | blinktrade.SimpleMarketMarketAlgo.prototype.makeTheMarket = function() { 214 | if (!this.calculateLimits()) { 215 | return; 216 | } 217 | 218 | var buy_sell_volume = this.getMyVolume(); 219 | var sum_buy_volume = buy_sell_volume[0]; 220 | var sum_sell_volume = buy_sell_volume[1]; 221 | 222 | 223 | // get customer balance 224 | var balance_crypto = this.application_.getBalance(this.symbol_.substr(0,3), 'available' ); 225 | var balance_fiat = this.application_.getBalance(this.symbol_.substr(3,3), 'available' ); 226 | 227 | var bid_price = (this.min_limit_bid_price_ + this.max_limit_bid_price_) / 2 ; 228 | var ask_price = (this.min_limit_ask_price_ + this.max_limit_ask_price_) / 2 ; 229 | 230 | var params = this.application_.getParameters(); 231 | 232 | // find the quantity to buy 233 | var limit_buy_volume = parseInt( params["limit"] * 1e8); 234 | if (limit_buy_volume > balance_fiat) { 235 | limit_buy_volume = balance_fiat; 236 | } 237 | var volume_to_buy = limit_buy_volume - sum_buy_volume; 238 | var qty_to_buy = 0; 239 | if ( volume_to_buy > 0 ) { 240 | qty_to_buy = parseInt(volume_to_buy / bid_price * 1e8, 10); 241 | } 242 | 243 | // find the quantity to sell 244 | var limit_sell_volume = parseInt( params["limit"] * 1e8 ); 245 | if (limit_sell_volume > (balance_crypto * ask_price / 1e8)) { 246 | limit_sell_volume = (balance_crypto * ask_price / 1e8); 247 | } 248 | var volume_to_sell = limit_sell_volume - sum_sell_volume; 249 | var qty_to_sell = parseInt(volume_to_sell / ask_price * 1e8 , 10) ; 250 | if (qty_to_sell > balance_crypto) { 251 | qty_to_sell = balance_crypto; 252 | } 253 | 254 | if (qty_to_buy > 100000){ 255 | this.application_.sendBuyLimitedOrder(qty_to_buy, bid_price); 256 | } 257 | if (qty_to_sell > 100000) { 258 | this.application_.sendSellLimitedOrder(qty_to_sell, ask_price); 259 | } 260 | }; 261 | 262 | blinktrade.SimpleMarketMarketAlgo.prototype.cancelOrdersOutsideOfLimits = function(){ 263 | if (!this.calculateLimits()) { 264 | return; 265 | } 266 | 267 | var my_orders = this.application_.getOpenOrders(); 268 | for (var order_id in my_orders) { 269 | var order = my_orders[order_id]; 270 | 271 | var is_an_order_sent_from_this_algo = (order['ClOrdID'].substr(0,4) == 'algo'); 272 | 273 | if (!is_an_order_sent_from_this_algo){ 274 | // order was not sent from this algo .... just continue to the next order 275 | continue; 276 | } 277 | 278 | 279 | var is_buy_order = (order['Side'] == '1' ); 280 | var is_sell_order = (order['Side'] == '2' ); 281 | 282 | // 283 | // let's cancel the order in case we don't know the limits 284 | // 285 | if (is_buy_order && (this.min_limit_bid_price_ == null) ) { 286 | this.application_.cancelOrder(order['ClOrdID']); 287 | continue; 288 | } 289 | 290 | if (is_sell_order && (this.min_limit_ask_price_ == null) ) { 291 | this.application_.cancelOrder(order['ClOrdID']); 292 | continue; 293 | } 294 | 295 | // 296 | // Let's now check if the order is within the limits 297 | // 298 | var is_order_outside_of_limits; 299 | if (is_buy_order) { 300 | is_order_outside_of_limits = !(order['Price'] >= this.min_limit_bid_price_ && order['Price'] <= this.max_limit_bid_price_); 301 | } else if (is_sell_order) { 302 | is_order_outside_of_limits = !(order['Price'] >= this.min_limit_ask_price_ && order['Price'] <= this.max_limit_ask_price_); 303 | } 304 | 305 | if (is_order_outside_of_limits) { 306 | // this order not within the limits .... cancel it and go to the next order 307 | this.application_.cancelOrder(order['ClOrdID']); 308 | continue; 309 | } 310 | } 311 | }; 312 | 313 | /** 314 | * @param {Object.} params 315 | */ 316 | blinktrade.SimpleMarketMarketAlgo.prototype.onUpdateParams = function(params) { 317 | this.cancelOrdersOutsideOfLimits(); 318 | this.makeTheMarket(); 319 | }; 320 | 321 | /** 322 | * Invoked whenever your balance change 323 | * @param {string} currency 324 | * @param {number} balance 325 | */ 326 | blinktrade.SimpleMarketMarketAlgo.prototype.onBalanceUpdate = function(currency, balance) { 327 | this.cancelOrdersOutsideOfLimits(); 328 | this.makeTheMarket(); 329 | }; 330 | 331 | //-----END ALGO----- 332 | -------------------------------------------------------------------------------- /algorithm_application.js: -------------------------------------------------------------------------------- 1 | // ==ClosureCompiler== 2 | // @compilation_level ADVANCED_OPTIMIZATIONS 3 | // @output_file_name default.js 4 | // @use_closure_library true 5 | // @externs_url https://raw.githubusercontent.com/blinktrade/algorithm-trading/master/algorithm_interface.js 6 | // ==/ClosureCompiler== 7 | 8 | goog.require('goog.array'); 9 | goog.require('goog.object'); 10 | 11 | 12 | /** 13 | * @param {string} instance_id 14 | * @param {string} websocket_url 15 | * @param {string} symbol 16 | * @param {Object.>} open_orders 17 | * @param {Object.} algorithm_definition 18 | * @param {Object.} balance 19 | * @param {function(Application,string): AlgorithmTradingInterface} fn_creator 20 | * @param {Array.=} opt_tickers 21 | * @constructor 22 | */ 23 | var Application = function( instance_id, websocket_url, symbol, open_orders, algorithm_definition,balance, fn_creator, opt_tickers) { 24 | this.websocket_url_ = websocket_url; 25 | this.instance_id_ = instance_id; 26 | this.selected_symbol_ = symbol; 27 | this.open_orders_ = open_orders; 28 | this.algorithm_definition_ = algorithm_definition; 29 | this.params_ = null; 30 | 31 | this.status_ws_open_ = false; 32 | this.status_received_full_refresh_ = false; 33 | this.status_received_security_status_ = false; 34 | this.status_started_ = false; 35 | this.trade_history_ = []; 36 | this.order_book_ = {}; 37 | this.tikers_ = [symbol]; 38 | if (goog.isDefAndNotNull(opt_tickers) && goog.isArrayLike(opt_tickers)) { 39 | this.tikers_ = opt_tickers; 40 | } 41 | this.balance_ = balance; 42 | 43 | this.ws_ = new WebSocket(this.websocket_url_); 44 | 45 | /** @type {AlgorithmTradingInterface} */ 46 | this.instance_ = fn_creator( this, symbol ); 47 | this.ws_.onopen = goog.bind(this.onWebSocketOpen_, this); 48 | this.ws_.onmessage = goog.bind(this.onWebSocketMessage_, this); 49 | this.ws_.onerror = goog.bind(this.onWebSocketError_, this); 50 | }; 51 | 52 | /** 53 | * @type {AlgorithmTradingInterface} 54 | */ 55 | Application.prototype.instance_; 56 | 57 | 58 | /** 59 | * Send a buy order 60 | * @param {number} qty The amount in satoshis 61 | * @param {number} price The price in satoshis 62 | * @param {number|string=} opt_clientOrderId Defaults to random generated number 63 | * @return {number|string} Returns the clientOrderId for this order. 64 | */ 65 | Application.prototype.sendBuyLimitedOrder = function( qty, price, opt_clientOrderId ) { 66 | var clientOrderId = opt_clientOrderId || 'algo_' + parseInt( 1e7 * Math.random() , 10 ); 67 | 68 | postMessage({ 'rep':'new_order_limited', 69 | 'instance':this.instance_id_, 70 | 'qty': qty, 71 | 'side': '1', // 1-Buy, 2-Sell 72 | 'price': price, 73 | 'client_order_id': clientOrderId 74 | }); 75 | 76 | return clientOrderId; 77 | }; 78 | 79 | 80 | /** 81 | * Send a sell order 82 | * @param {number} qty The amount in satoshis 83 | * @param {number} price The price in satoshis 84 | * @param {number|string=} opt_clientOrderId Defaults to random generated number 85 | * @return {number|string} Returns the clientOrderId for this order. 86 | */ 87 | Application.prototype.sendSellLimitedOrder = function( qty, price, opt_clientOrderId ) { 88 | var clientOrderId = opt_clientOrderId || 'algo_' + parseInt( 1e7 * Math.random() , 10 ); 89 | 90 | postMessage({ 'rep':'new_order_limited', 91 | 'instance':this.instance_id_, 92 | 'qty': qty, 93 | 'side': '2', // 1-Buy, 2-Sell 94 | 'price': price, 95 | 'client_order_id': clientOrderId 96 | }); 97 | 98 | return clientOrderId; 99 | }; 100 | 101 | 102 | /** 103 | * Cancel an order. You must pass opt_clientOrderId nor opt_orderId 104 | * @param {number|string=} opt_clientOrderId Defaults to random generated number 105 | * @param {number=} opt_orderId 106 | */ 107 | Application.prototype.cancelOrder = function( opt_clientOrderId, opt_orderId ) { 108 | if (!goog.isDefAndNotNull(opt_clientOrderId) && !(goog.isDefAndNotNull(opt_orderId))){ 109 | this.stop('Invalid paramaters. Missing opt_clientOrderId or opt_orderId'); 110 | return; 111 | } 112 | 113 | if (goog.isDefAndNotNull(opt_clientOrderId) && (goog.isDefAndNotNull(opt_orderId))){ 114 | this.stop('Invalid paramaters. You must passa either opt_clientOrderId or opt_orderId'); 115 | return; 116 | } 117 | 118 | if (goog.isDefAndNotNull(opt_clientOrderId)) { 119 | goog.object.remove(this.open_orders_, /** @type {string} */(opt_clientOrderId)); 120 | } else if (goog.isDefAndNotNull(opt_orderId)) { 121 | var client_order_id = goog.object.findKey( this.open_orders_, function( order ){ 122 | return (order['OrderID'] == opt_orderId); 123 | }); 124 | if (goog.isDefAndNotNull(client_order_id)) { 125 | goog.object.remove(this.open_orders_, /** @type {string} */(client_order_id)); 126 | } 127 | } 128 | 129 | postMessage({ 'rep':'cancel_order', 130 | 'instance':this.instance_id_, 131 | 'client_order_id': opt_clientOrderId, 132 | 'order_id': opt_orderId 133 | }); 134 | }; 135 | 136 | /** 137 | * Cancel all orders. 138 | */ 139 | Application.prototype.cancelAllOrders = function() { 140 | postMessage({ 'rep':'cancel_order', 'instance':this.instance_id_ }); 141 | }; 142 | 143 | 144 | 145 | /** 146 | * Returns an object with all bids and asks 147 | * @return {Object.>>} 148 | * The returned Object structure is: 149 | * { 150 | * 'bids' : [ [price, qty], [price, qty], ... [price, qty] ], 151 | * 'asks' : [ [price, qty], [price, qty], ... [price, qty] ] 152 | * } 153 | */ 154 | Application.prototype.getOrderBook = function() { 155 | return this.order_book_[this.selected_symbol_]; 156 | }; 157 | 158 | /** 159 | * Returns user balance for the given currency 160 | * @param {string} currency 161 | * @param {AlgorithmTradingInterface.BalanceType} type 162 | * return {number} 163 | */ 164 | Application.prototype.getBalance = function( currency, type ) { 165 | if (type == "deposit") { 166 | return this.balance_[currency]; 167 | 168 | } else if (type == "available") { 169 | if (goog.isDefAndNotNull(this.balance_[currency + '_locked'])) { 170 | return this.balance_[currency] - this.balance_[currency + '_locked']; 171 | } else if (goog.isDefAndNotNull(this.balance_[currency])) { 172 | return this.balance_[currency]; 173 | } else { 174 | return 0; 175 | } 176 | } else if (goog.isDefAndNotNull(type)) { 177 | return this.balance_[currency + '_' + type]; 178 | } else { 179 | return this.balance_[currency]; 180 | } 181 | }; 182 | 183 | 184 | 185 | /** 186 | * Return an array containing all trades that occurred in the past 24 hours 187 | * @return {Array.} 188 | * The returned Object structure is: 189 | * MDEntryBuyerID: 90800013. => The buyer account id 190 | * MDEntryDate: "2014-11-30" => Date of the Trade represented in UTC, Format: YYYY-MM-DD 191 | * MDEntryTime: "09:32:05" => Time of the Trade represented in UTC, Format: HH:MM:SS 192 | * MDEntryPx: 50100000000 => Price per share 193 | * MDEntrySellerID: 90000002 => The seller account id 194 | * MDEntrySize: 1000000 => Volume of the trade 195 | * MDEntryType: "2" => Type Market Data entry. Always 2 - Trade 196 | * OrderID: 392 => Unique identifier for Order as assigned by the exchange 197 | * SecondaryOrderID: 384 => Counter party OrderID 198 | * Side: "1" => Side of the execution. 1-Buy, 2-Sell 199 | * Symbol: "BTCUSD" => Ticker symbol 200 | * Timestamp: [native Object] => Javascript Date object representation of MDEntryDate+MDEntryTime 201 | * TradeID: 183 => Trade identification 202 | */ 203 | Application.prototype.getTrades = function() { 204 | return this.trade_history_; 205 | }; 206 | 207 | /** 208 | * Return the parameters previously set. 209 | * @return {Object.} 210 | */ 211 | Application.prototype.getParameters = function() { 212 | return this.params_; 213 | }; 214 | 215 | /** 216 | * Returns all open orders. 217 | * The returned Object structure is: 218 | * Key: OrderID. 219 | * Value: Another key/value object with all order fields and its values. Example: 220 | * AvgPx: 39000000000 => Calculated average price of all fills on this order. 221 | * ClOrdID: "2414949" => Unique identifier for Order as assigned by you during the order creation. 222 | * CumQty: 96300000 => Total number of shares filled. 223 | * CxlQty: 0 => Total number of shares canceled for this order. 224 | * LeavesQty: 403700000 => Amount of shares open for further execution. 225 | * OrdStatus: "1" => Identifies current status of order. 0-New, 1-Partially filled, 2-Filled, 4-Canceled 226 | * OrdType: "2" => Order type. 1-Market, 2-Limited, 3-Stop, 4-Stop Limit 227 | * OrderDate: "2014-11-29 21:06:04" => Time/date combination represented in UTC, Format: YYYY-MM-DD HH:MM:SS 228 | * OrderID: 100 => Unique identifier for Order as assigned by the exchange 229 | * OrderQty: 500000000 => Quantity ordered 230 | * Price: 39000000000 => Price per unit of quantity 231 | * Side: "2" => Side of order, 1-Buy, 2-Sell 232 | * Symbol: "BTCUSD" => Ticker symbol 233 | * TimeInForce: "1" => Specifies how long the order remains in effect. 0-Day, 1-Good Till Cancel(GTC) 234 | * Volume: 37557000000 => Total volume traded. CumQty * AvgPx 235 | * @return {Object}. 236 | */ 237 | Application.prototype.getOpenOrders = function() { 238 | return this.open_orders_; 239 | }; 240 | 241 | 242 | /** 243 | * @return {string}. Returns the market in which the algorithm will send its orders. 244 | */ 245 | Application.prototype.getMarket = function() { 246 | return this.selected_symbol_; 247 | }; 248 | 249 | /** 250 | * @return {string}. Returns the algorithm GUID instance id. 251 | */ 252 | Application.prototype.getInstanceID = function() { 253 | return this.instance_id_; 254 | }; 255 | 256 | /** 257 | * Show a notification to the user 258 | * @param {string} title 259 | * @param {string} description 260 | * @param {string=} opt_type Defaults to "info". It can be one of the following values "info", "success", "error" 261 | */ 262 | Application.prototype.showNotification = function(title, description, opt_type) { 263 | var notification_type = opt_type | "info"; 264 | postMessage({'rep':'notification', 265 | 'instance':this.instance_id_, 266 | 'type': notification_type, 267 | 'title': title, 268 | 'description': description }); 269 | }; 270 | 271 | /** 272 | * Terminates the algorithm. 273 | * @param {string=} opt_error_message An error notification will be shown in filled. 274 | */ 275 | Application.prototype.stop = function(opt_error_message) { 276 | try { 277 | if (this.status_started_) { 278 | this.instance_.stop(); 279 | this.status_started_ = false; 280 | } 281 | } catch(e) {} 282 | 283 | if (opt_error_message == null){ 284 | postMessage({'rep':'stop', 'instance':this.instance_id_ }); 285 | } else { 286 | postMessage({'rep':'stop', 'instance':this.instance_id_, 'error':opt_error_message }); 287 | } 288 | }; 289 | 290 | 291 | 292 | 293 | 294 | Application.prototype.onWebSocketOpen_ = function(e) { 295 | this.status_ws_open_ = true; 296 | postMessage({'rep':'create', 'instance':this.instance_id_, 'status':'ws_open' }); 297 | 298 | var mdRequestId = parseInt( 1e7 * Math.random() , 10 ); 299 | 300 | var instruments = [this.selected_symbol_]; 301 | 302 | var msgSubscribeMarketData = { 303 | 'MsgType': 'V', 304 | 'MDReqID': mdRequestId, 305 | 'SubscriptionRequestType': '1', 306 | 'MarketDepth': 0, 307 | 'MDUpdateType': '1', 308 | 'MDEntryTypes': ['0', '1', '2'], 309 | 'Instruments': instruments 310 | }; 311 | this.ws_.send(JSON.stringify(msgSubscribeMarketData)); 312 | 313 | var msgSubscribeSecurityStatus = { 314 | 'MsgType': 'e', 315 | 'SecurityStatusReqID': parseInt( 1e7 * Math.random() , 10 ), 316 | 'SubscriptionRequestType': '1', 317 | 'Instruments': this.tikers_ 318 | }; 319 | this.ws_.send(JSON.stringify(msgSubscribeSecurityStatus)); 320 | 321 | setTimeout( goog.bind(this.sendTestRequest_, this), 30000); 322 | }; 323 | 324 | Application.prototype.sendTestRequest_ = function() { 325 | var msgTestRequest = { 326 | 'MsgType': '1', 327 | 'TestReqID': parseInt( 1e7 * Math.random() , 10 ), 328 | 'SendTime': new Date().getTime() 329 | }; 330 | this.ws_.send(JSON.stringify(msgTestRequest)); 331 | }; 332 | 333 | Application.prototype.start_ = function(params) { 334 | if ( this.status_started_ ) { 335 | return; 336 | } 337 | 338 | try { 339 | this.params_ = params; 340 | this.instance_.start(params); 341 | this.status_started_ = true; 342 | } catch(e) {} 343 | 344 | postMessage({'rep':'start', 'instance':this.instance_id_}); 345 | }; 346 | 347 | /** 348 | * @param {string=} error_message 349 | */ 350 | Application.prototype.terminate_ = function(error_message) { 351 | try { 352 | if (this.status_started_) { 353 | this.instance_.stop(); 354 | this.status_started_ = false; 355 | } 356 | } catch(e) {} 357 | 358 | if (error_message == null){ 359 | postMessage({'rep':'terminate', 'instance':this.instance_id_ }); 360 | } else { 361 | postMessage({'rep':'terminate', 'instance':this.instance_id_, 'error':error_message }); 362 | } 363 | }; 364 | 365 | /** 366 | * @param {Object} msg 367 | */ 368 | Application.prototype.processBalanceMsg_ = function(msg) { 369 | goog.object.extend(this.balance_, msg); 370 | try { 371 | goog.object.forEach( msg, function(balance, currency ) { 372 | if (currency.substring(4) == 'locked') { 373 | this.instance_.onBalanceUpdate(currency.substring(0,3), balance, AlgorithmTradingInterface.BalanceType.LOCKED); 374 | } else { 375 | this.instance_.onBalanceUpdate(currency, balance, AlgorithmTradingInterface.BalanceType.DEPOSIT); 376 | } 377 | }, this ); 378 | } catch(e) {} 379 | postMessage({'rep':'balance', 'instance':this.instance_id_}); 380 | }; 381 | 382 | 383 | /** 384 | * @param {Object} msg 385 | */ 386 | Application.prototype.processParamsMsg_ = function(msg) { 387 | this.params_ = msg; 388 | try { 389 | this.instance_.onUpdateParams(msg); 390 | } catch(e) {} 391 | postMessage({'rep':'params', 'instance':this.instance_id_}); 392 | }; 393 | 394 | /** 395 | * @param {Object} msg 396 | */ 397 | Application.prototype.processExecutionReportMsg_ = function(msg) { 398 | if (msg['OrdStatus'] == '2' || msg['OrdStatus'] == '4' ) { 399 | goog.object.remove(this.open_orders_, /** @type {string} */(msg['ClOrdID'] )); 400 | } else { 401 | if (msg['OrdStatus'] == 'A') { 402 | this.open_orders_[msg['ClOrdID'] ] = msg; 403 | } else { 404 | if (msg['OrdStatus'] == '0'){ 405 | goog.object.remove(this.open_orders_, /** @type {string} */(msg['ClOrdID'] )); 406 | } 407 | this.open_orders_[msg['ClOrdID'] ] = msg; 408 | } 409 | } 410 | 411 | try { 412 | this.instance_.onExecutionReport(msg); 413 | } catch(e) {} 414 | 415 | postMessage({'rep':'execution_report', 'instance':this.instance_id_}); 416 | }; 417 | 418 | 419 | Application.prototype.onWebSocketError_ = function (e) { 420 | this.terminate_(e.data); 421 | }; 422 | 423 | Application.prototype.onTicker_ = function(msg) { 424 | if (!this.status_started_) { 425 | return; 426 | } 427 | 428 | try { 429 | this.instance_.onTicker(msg); 430 | } catch(e) {} 431 | }; 432 | 433 | Application.prototype.onMDNewOrder_ = function(msg) { 434 | var symbol = msg['Symbol']; 435 | var side = msg['MDEntryType']; 436 | var index = msg['MDEntryPositionNo'] - 1; 437 | var price = msg['MDEntryPx']; 438 | var qty = msg['MDEntrySize']; 439 | 440 | if ( this.order_book_[symbol] == null ) { 441 | this.order_book_[symbol] = {'bids': [], 'asks':[] }; 442 | } 443 | 444 | if (side == '0') { 445 | goog.array.insertAt(this.order_book_[symbol]['bids'], [price, qty], index); 446 | } else if (side == '1') { 447 | goog.array.insertAt(this.order_book_[symbol]['asks'], [price, qty], index); 448 | } 449 | 450 | if (!this.status_started_) { 451 | return; 452 | } 453 | 454 | try { 455 | this.instance_.onOrderBookNewOrder(msg); 456 | } catch(e) {} 457 | }; 458 | 459 | Application.prototype.onMDUpdateOrder_ = function(msg) { 460 | var symbol = msg['Symbol']; 461 | var side = msg['MDEntryType']; 462 | var index = msg['MDEntryPositionNo'] - 1; 463 | var qty = msg['MDEntrySize']; 464 | 465 | if (side == '0') { 466 | this.order_book_[symbol]['bids'][index] = [this.order_book_[symbol]['bids'][index][0], qty]; 467 | } else if (side == '1') { 468 | this.order_book_[symbol]['asks'][index] = [this.order_book_[symbol]['asks'][index][0], qty]; 469 | } 470 | 471 | if (!this.status_started_) { 472 | return; 473 | } 474 | 475 | try { 476 | this.instance_.onOrderBookUpdateOrder(msg); 477 | } catch(e) {} 478 | }; 479 | 480 | Application.prototype.onMDDeleteOrder_ = function(msg) { 481 | var symbol = msg['Symbol']; 482 | var index = msg['MDEntryPositionNo'] - 1; 483 | var side = msg['MDEntryType']; 484 | 485 | if (side == '0') { 486 | this.order_book_[symbol]['bids'].splice(index,1); 487 | } else if (side == '1') { 488 | this.order_book_[symbol]['asks'].splice(index,1); 489 | } 490 | 491 | if (!this.status_started_) { 492 | return; 493 | } 494 | 495 | try { 496 | this.instance_.onOrderBookDeleteOrder(msg); 497 | } catch(e) {} 498 | }; 499 | 500 | Application.prototype.onMDDeleteOrderThru_ = function(msg) { 501 | var symbol = msg['Symbol']; 502 | var index = msg['MDEntryPositionNo']; 503 | var side = msg['MDEntryType']; 504 | 505 | if (side == '0') { 506 | this.order_book_[symbol]['bids'].splice(0, index); 507 | } else if (side == '1') { 508 | this.order_book_[symbol]['asks'].splice(0, index); 509 | } 510 | 511 | if (!this.status_started_) { 512 | return; 513 | } 514 | 515 | try { 516 | this.instance_.onOrderBookDeleteOrdersThru(msg); 517 | } catch(e) {} 518 | }; 519 | 520 | Application.prototype.onMDTrade_ = function(msg) { 521 | var timestamp = new Date(); 522 | var create_date_parts = msg['MDEntryDate'].split('-'); 523 | var create_time_parts = msg['MDEntryTime'].split(':'); 524 | timestamp.setUTCFullYear(create_date_parts[0]); 525 | timestamp.setUTCMonth(create_date_parts[1]); 526 | timestamp.setUTCDate(create_date_parts[2]); 527 | timestamp.setUTCHours(create_time_parts[0]); 528 | timestamp.setUTCMinutes(create_time_parts[1]); 529 | timestamp.setUTCSeconds(create_time_parts[2]); 530 | msg["Timestamp"] = timestamp; 531 | 532 | this.trade_history_.push( msg ); 533 | 534 | if (!this.status_started_) { 535 | return; 536 | } 537 | 538 | try { 539 | this.instance_.onTrade(msg); 540 | } catch(e) {} 541 | }; 542 | 543 | Application.prototype.onWebSocketMessage_ = function (e) { 544 | var msg = JSON.parse(e.data); 545 | 546 | var msg_type = msg['MsgType']; 547 | delete msg['MsgType']; 548 | 549 | switch( msg_type ) { 550 | case 'f': 551 | this.onTicker_(msg); 552 | if (!this.status_received_security_status_) { 553 | postMessage({'rep':'create', 'instance':this.instance_id_, 'status':'received_security_status' }); 554 | } 555 | this.status_received_security_status_ = true; 556 | break; 557 | case 'W': 558 | for ( var x in msg['MDFullGrp']) { 559 | var entry = msg['MDFullGrp'][x]; 560 | entry['MDReqID'] = msg['MDReqID']; 561 | switch (entry['MDEntryType']) { 562 | case '0': // Bid 563 | case '1': // Offer 564 | entry['Symbol'] = msg['Symbol']; 565 | this.onMDNewOrder_(entry); 566 | break; 567 | case '2': // Trade 568 | this.onMDTrade_(entry); 569 | break; 570 | } 571 | } 572 | if (!this.status_received_full_refresh_) { 573 | postMessage({'rep':'create', 'instance':this.instance_id_, 'status':'received_full_refresh' }); 574 | } 575 | this.status_received_full_refresh_ = true; 576 | break; 577 | case 'X': 578 | var has_order_book_changed = false; 579 | for ( var y in msg['MDIncGrp']) { 580 | var xentry = msg['MDIncGrp'][y]; 581 | xentry['MDReqID'] = msg['MDReqID']; 582 | switch (xentry['MDEntryType']) { 583 | case '0': // Bid 584 | case '1': // Offer 585 | has_order_book_changed = true; 586 | switch( xentry['MDUpdateAction'] ) { 587 | case '0': 588 | this.onMDNewOrder_(xentry); 589 | break; 590 | case '1': 591 | this.onMDUpdateOrder_(xentry); 592 | break; 593 | case '2': 594 | this.onMDDeleteOrder_(xentry); 595 | break; 596 | case '3': 597 | this.onMDDeleteOrderThru_(xentry); 598 | break; 599 | } 600 | break; 601 | case '2': // Trade 602 | this.onMDTrade_(xentry); 603 | break; 604 | } 605 | } 606 | 607 | try { 608 | if (this.status_started_ && has_order_book_changed) { 609 | this.instance_.onOrderBookChange(this.order_book_[this.selected_symbol_]); 610 | } 611 | } catch(e) {} 612 | break; 613 | } 614 | }; 615 | 616 | var _app; 617 | addEventListener('message', function(e) { 618 | try { 619 | var data = e.data; 620 | switch (data['req']) { 621 | case 'create': 622 | /** 623 | * @type {function(Application,string): AlgorithmTradingInterface} 624 | */ 625 | var creator_fn = /** @type {function(Application,string): AlgorithmTradingInterface} */ (eval(context["algo_definition"]['creator'])); 626 | 627 | _app = new Application(context["algo_instance_id"], 628 | context["wss_url"], 629 | context["symbol"], 630 | context["open_orders"], 631 | context["algo_definition"], 632 | context["balance"], 633 | creator_fn, 634 | context["tickers"]); 635 | break; 636 | case 'start': 637 | _app.start_(data['params']); 638 | break; 639 | case 'params': 640 | _app.processParamsMsg_( data['params'] ); 641 | break; 642 | case 'execution_report': 643 | _app.processExecutionReportMsg_( data['execution_report'] ); 644 | break; 645 | case 'stop': 646 | _app.stop(); 647 | self.close(); 648 | break; 649 | case 'balance': 650 | _app.processBalanceMsg_( data['balances'] ); 651 | break; 652 | } 653 | } catch (error) { 654 | if (_app != null) { 655 | _app.terminate_(error.message); 656 | } 657 | self.close(); 658 | } 659 | }, false); 660 | 661 | 662 | goog.exportSymbol('goog.bind', goog.bind); 663 | goog.exportSymbol('goog.isDefAndNotNull', goog.isDefAndNotNull); 664 | goog.exportSymbol('goog.typeOf',goog.typeOf); 665 | goog.exportSymbol('goog.isDef',goog.isDef); 666 | goog.exportSymbol('goog.isNull',goog.isNull); 667 | goog.exportSymbol('goog.isArray',goog.isArray); 668 | goog.exportSymbol('goog.isArrayLike',goog.isArrayLike); 669 | goog.exportSymbol('goog.isDateLike',goog.isDateLike); 670 | goog.exportSymbol('goog.isString',goog.isString); 671 | goog.exportSymbol('goog.isBoolean',goog.isBoolean); 672 | goog.exportSymbol('goog.isNumber',goog.isNumber); 673 | goog.exportSymbol('goog.isFunction',goog.isFunction); 674 | goog.exportSymbol('goog.isObject',goog.isObject ); 675 | goog.exportSymbol('goog.cloneObject',goog.cloneObject); 676 | goog.exportSymbol('goog.partial',goog.partial); 677 | goog.exportSymbol('goog.mixin',goog.mixin); 678 | goog.exportSymbol('goog.now',goog.now); 679 | goog.exportSymbol('goog.globalEval',goog.globalEval); 680 | goog.exportSymbol('goog.inherits',goog.inherits); 681 | goog.exportSymbol('goog.base',goog.base); 682 | 683 | 684 | 685 | 686 | goog.exportSymbol('goog.array.splice', goog.array.splice); 687 | goog.exportSymbol('goog.array.insertAt', goog.array.insertAt); 688 | goog.exportSymbol('goog.array.indexOf', goog.array.indexOf); 689 | goog.exportSymbol('goog.array.lastIndexOf',goog.array.lastIndexOf); 690 | goog.exportSymbol('goog.array.forEach',goog.array.forEach); 691 | goog.exportSymbol('goog.array.forEachRight',goog.array.forEachRight); 692 | goog.exportSymbol('goog.array.filter',goog.array.filter); 693 | goog.exportSymbol('goog.array.map',goog.array.map); 694 | goog.exportSymbol('goog.array.reduce',goog.array.reduce); 695 | goog.exportSymbol('goog.array.reduceRight',goog.array.reduceRight); 696 | goog.exportSymbol('goog.array.some',goog.array.some); 697 | goog.exportSymbol('goog.array.every',goog.array.every); 698 | goog.exportSymbol('goog.array.count',goog.array.count); 699 | goog.exportSymbol('goog.array.findIndex',goog.array.findIndex); 700 | goog.exportSymbol('goog.array.findRight',goog.array.findRight); 701 | goog.exportSymbol('goog.array.findIndexRight',goog.array.findIndexRight); 702 | goog.exportSymbol('goog.array.contains',goog.array.contains); 703 | goog.exportSymbol('goog.array.isEmpty',goog.array.isEmpty); 704 | goog.exportSymbol('goog.array.clear',goog.array.clear); 705 | goog.exportSymbol('goog.array.insert',goog.array.insert); 706 | goog.exportSymbol('goog.array.insertArrayAt',goog.array.insertArrayAt); 707 | goog.exportSymbol('goog.array.insertBefore',goog.array.insertBefore); 708 | goog.exportSymbol('goog.array.remove',goog.array.remove); 709 | goog.exportSymbol('goog.array.removeAt',goog.array.removeAt); 710 | goog.exportSymbol('goog.array.removeIf',goog.array.removeIf); 711 | goog.exportSymbol('goog.array.concat',goog.array.concat); 712 | goog.exportSymbol('goog.array.toArray',goog.array.toArray); 713 | goog.exportSymbol('goog.array.clone',goog.array.clone); 714 | goog.exportSymbol('goog.array.extend',goog.array.extend); 715 | goog.exportSymbol('goog.array.slice',goog.array.slice); 716 | goog.exportSymbol('goog.array.removeDuplicates',goog.array.removeDuplicates); 717 | goog.exportSymbol('goog.array.binarySearch',goog.array.binarySearch); 718 | goog.exportSymbol('goog.array.binarySelect',goog.array.binarySelect); 719 | goog.exportSymbol('goog.array.sort',goog.array.sort); 720 | goog.exportSymbol('goog.array.stableSort',goog.array.stableSort); 721 | goog.exportSymbol('goog.array.sortObjectsByKey',goog.array.sortObjectsByKey); 722 | goog.exportSymbol('goog.array.isSorted',goog.array.isSorted); 723 | goog.exportSymbol('goog.array.equals',goog.array.equals); 724 | goog.exportSymbol('goog.array.compare3',goog.array.compare3); 725 | goog.exportSymbol('goog.array.defaultCompare',goog.array.defaultCompare); 726 | goog.exportSymbol('goog.array.defaultCompareEquality',goog.array.defaultCompareEquality); 727 | goog.exportSymbol('goog.array.binaryInsert',goog.array.binaryInsert); 728 | goog.exportSymbol('goog.array.binaryRemove',goog.array.binaryRemove); 729 | goog.exportSymbol('goog.array.bucket',goog.array.bucket); 730 | goog.exportSymbol('goog.array.toObject',goog.array.toObject); 731 | goog.exportSymbol('goog.array.range',goog.array.range); 732 | goog.exportSymbol('goog.array.repeat',goog.array.repeat); 733 | goog.exportSymbol('goog.array.flatten',goog.array.flatten); 734 | goog.exportSymbol('goog.array.rotate',goog.array.rotate); 735 | goog.exportSymbol('goog.array.zip',goog.array.zip) 736 | goog.exportSymbol('goog.array.shuffle',goog.array.shuffle); 737 | 738 | 739 | 740 | goog.exportSymbol('goog.object.forEach', goog.object.forEach); 741 | goog.exportSymbol('goog.object.extend', goog.object.extend); 742 | goog.exportSymbol('goog.object.filter',goog.object.filter); 743 | goog.exportSymbol('goog.object.map',goog.object.map); 744 | goog.exportSymbol('goog.object.some',goog.object.some); 745 | goog.exportSymbol('goog.object.every',goog.object.every); 746 | goog.exportSymbol('goog.object.getCount',goog.object.getCount); 747 | goog.exportSymbol('goog.object.getAnyKey',goog.object.getAnyKey); 748 | goog.exportSymbol('goog.object.getAnyValue',goog.object.getAnyValue); 749 | goog.exportSymbol('goog.object.contains',goog.object.contains); 750 | goog.exportSymbol('goog.object.getValues',goog.object.getValues); 751 | goog.exportSymbol('goog.object.getKeys',goog.object.getKeys); 752 | goog.exportSymbol('goog.object.getValueByKeys',goog.object.getValueByKeys); 753 | goog.exportSymbol('goog.object.containsKey',goog.object.containsKey); 754 | goog.exportSymbol('goog.object.containsValue',goog.object.containsValue); 755 | goog.exportSymbol('goog.object.findKey',goog.object.findKey); 756 | goog.exportSymbol('goog.object.findValue',goog.object.findValue); 757 | goog.exportSymbol('goog.object.isEmpty',goog.object.isEmpty); 758 | goog.exportSymbol('goog.object.clear',goog.object.clear); 759 | goog.exportSymbol('goog.object.remove',goog.object.remove); 760 | goog.exportSymbol('goog.object.add',goog.object.add); 761 | goog.exportSymbol('goog.object.get',goog.object.get); 762 | goog.exportSymbol('goog.object.set',goog.object.set); 763 | goog.exportSymbol('goog.object.setIfUndefined',goog.object.setIfUndefined); 764 | goog.exportSymbol('goog.object.clone',goog.object.clone); 765 | goog.exportSymbol('goog.object.unsafeClone',goog.object.unsafeClone); 766 | goog.exportSymbol('goog.object.transpose',goog.object.transpose); 767 | goog.exportSymbol('goog.object.create',goog.object.create); 768 | goog.exportSymbol('goog.object.createSet',goog.object.createSet); 769 | goog.exportSymbol('goog.object.createImmutableView',goog.object.createImmutableView); 770 | goog.exportSymbol('goog.object.isImmutableView',goog.object.isImmutableView); 771 | 772 | 773 | 774 | goog.exportSymbol('Application', Application); 775 | goog.exportProperty(Application.prototype, 'sendBuyLimitedOrder', Application.prototype.sendBuyLimitedOrder); 776 | goog.exportProperty(Application.prototype, 'sendSellLimitedOrder', Application.prototype.sendSellLimitedOrder); 777 | goog.exportProperty(Application.prototype, 'cancelAllOrders', Application.prototype.cancelAllOrders); 778 | goog.exportProperty(Application.prototype, 'cancelOrder', Application.prototype.cancelOrder); 779 | goog.exportProperty(Application.prototype, 'getOrderBook', Application.prototype.getOrderBook); 780 | goog.exportProperty(Application.prototype, 'getTrades', Application.prototype.getTrades); 781 | goog.exportProperty(Application.prototype, 'getBalance', Application.prototype.getBalance); 782 | goog.exportProperty(Application.prototype, 'getParameters', Application.prototype.getParameters); 783 | goog.exportProperty(Application.prototype, 'getOpenOrders', Application.prototype.getOpenOrders); 784 | goog.exportProperty(Application.prototype, 'getMarket', Application.prototype.getMarket); 785 | goog.exportProperty(Application.prototype, 'getInstanceID', Application.prototype.getInstanceID); 786 | goog.exportProperty(Application.prototype, 'showNotification', Application.prototype.showNotification); 787 | goog.exportProperty(Application.prototype, 'stop', Application.prototype.stop); 788 | 789 | 790 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------