├── db └── .keep ├── docs ├── .keep ├── ws_api.md └── server.md ├── test └── todo.js ├── res └── ad_screenshot.png ├── index.js ├── lib ├── wss │ ├── send.js │ ├── events │ │ ├── on_disconnect.js │ │ ├── on_connect.js │ │ └── on_message.js │ ├── cmds │ │ ├── stop_ao.js │ │ ├── submit_ao.js │ │ └── get_all_aos.js │ └── start_wss.js ├── ws │ ├── notify_ao_refresh.js │ ├── notify_res_error.js │ └── notify_res.js └── server.js ├── .gitignore ├── .travis.yml ├── .env.example ├── .github ├── ISSUE_TEMPLATE └── PULL_REQUEST_TEMPLATE ├── examples ├── submit_ao_ws.js └── server.js ├── CHANGELOG ├── package.json ├── README.md └── LICENSE /db/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/todo.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | -------------------------------------------------------------------------------- /res/ad_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfinexcom/bfx-hf-algo-server/HEAD/res/ad_screenshot.png -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const AOServer = require('./lib/server') 4 | 5 | module.exports = AOServer 6 | -------------------------------------------------------------------------------- /lib/wss/send.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | module.exports = (ws, msg = []) => { 4 | ws.send(JSON.stringify(msg)) 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | dist/* 3 | node_modules 4 | npm-debug.log 5 | .vscode 6 | *.swo 7 | *.swp 8 | .DS_Store 9 | coverage 10 | .env 11 | !db/.keep 12 | package-lock.json 13 | db/* 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: node_js 4 | node_js: 5 | - "12" 6 | 7 | install: 8 | - npm install 9 | 10 | script: 11 | - npm run lint 12 | - npm run unit 13 | -------------------------------------------------------------------------------- /lib/ws/notify_ao_refresh.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const notifyRes = require('./notify_res') 4 | 5 | module.exports = (asState = {}) => { 6 | notifyRes(asState, Date.now(), 'ucm-ao-reload-req') 7 | } 8 | -------------------------------------------------------------------------------- /lib/wss/events/on_disconnect.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const debug = require('debug')('bfx:hf:algo-server:wss:events:on-disconnect') 4 | 5 | module.exports = (asState, ws) => { 6 | debug('ws client disconnected') 7 | } 8 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | DB_FILENAME=db/algo-server-db.json 2 | 3 | API_KEY=... 4 | API_SECRET=... 5 | 6 | # PLATFORM=ethfinex 7 | # WS_URL=wss://api.ethfinex.com/ws/2 8 | # REST_URL=https://api.ethfinex.com 9 | # SOCKS_PROXY_URL=socks4://127.0.0.1:9998 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE: -------------------------------------------------------------------------------- 1 | #### Issue type 2 | - [ ] bug 3 | - [ ] missing functionality 4 | - [ ] performance 5 | - [ ] feature request 6 | 7 | #### Brief description 8 | 9 | #### Steps to reproduce 10 | - 11 | 12 | ##### Additional Notes: 13 | - 14 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE: -------------------------------------------------------------------------------- 1 | ### Description: 2 | ... 3 | 4 | ### Breaking changes: 5 | - [ ] 6 | 7 | ### New features: 8 | - [ ] 9 | 10 | ### Fixes: 11 | - [ ] 12 | 13 | ### PR status: 14 | - [ ] Version bumped 15 | - [ ] Change-log updated 16 | - [ ] Tests added or updated 17 | - [ ] Documentation updated 18 | -------------------------------------------------------------------------------- /lib/ws/notify_res_error.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const notifyRes = require('./notify_res') 4 | 5 | module.exports = (asState, mid, type, err) => { 6 | const message = err instanceof Error ? err.message : err 7 | 8 | notifyRes(asState, mid, type, { 9 | notify: { 10 | level: 'error', 11 | message 12 | } 13 | }) 14 | } 15 | -------------------------------------------------------------------------------- /lib/wss/cmds/stop_ao.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const debug = require('debug')('bfx:hf:algo-server:wss:cmd:stop-ao') 4 | const send = require('../send') 5 | 6 | module.exports = async (as, ws, msg) => { 7 | const [, gid] = msg 8 | 9 | try { 10 | await as.host.stopAO(+gid) 11 | } catch (e) { 12 | send(ws, ['error', e.message]) 13 | debug('%s', e.stack) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/wss/cmds/submit_ao.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const debug = require('debug')('bfx:hf:algo-server:wss:cmd:submit-ao') 4 | const send = require('../send') 5 | 6 | module.exports = async (as, ws, msg) => { 7 | const [, type, params] = msg 8 | 9 | try { 10 | await as.host.startAO(type, params) 11 | } catch (e) { 12 | send(ws, ['error', e.message]) 13 | debug('%s', e.stack) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/wss/cmds/get_all_aos.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const send = require('../send') 4 | 5 | module.exports = async (as, ws) => { 6 | const { db } = as 7 | const { AlgoOrder } = db 8 | const aos = await AlgoOrder.getAll() 9 | 10 | send(ws, ['data.aos', Object.values(aos).map(ao => ([ 11 | ao.gid, 12 | ao.algoID, 13 | ao.active, 14 | ao.state, 15 | +(new Date(+ao.gid)) // created 16 | ]))]) 17 | } 18 | -------------------------------------------------------------------------------- /lib/wss/start_wss.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const debug = require('debug')('bfx:hf:algo-server:wss:start-wss') 4 | const WS = require('ws') 5 | const onWSConnected = require('./events/on_connect') 6 | 7 | module.exports = (asState) => { 8 | const { port } = asState 9 | const wss = new WS.Server({ port }) 10 | 11 | wss.on('connection', ws => { 12 | onWSConnected(asState, ws) 13 | }) 14 | 15 | debug(`websocket API open on localhost:${port}`) 16 | 17 | return wss 18 | } 19 | -------------------------------------------------------------------------------- /lib/ws/notify_res.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | /** 4 | * Responds to an incoming broadcast by ID 5 | * 6 | * @param {Object} asState 7 | * @param {number} mid - incoming broadcast ID 8 | * @param {string} type - incoming broadcast type 9 | * @param {Object} info - broadcast data 10 | */ 11 | module.exports = (asState, mid, type, info = {}) => { 12 | const { adapter } = asState 13 | const t = type.split('-') 14 | t[3] = 'res' 15 | 16 | adapter.sendWithAnyConnection([0, 'n', null, { 17 | mid: mid + 1, 18 | type: t.join('-'), 19 | info 20 | }]) 21 | } 22 | -------------------------------------------------------------------------------- /lib/wss/events/on_connect.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const debug = require('debug')('bfx:hf:algo-server:wss:events:on-connect') 4 | const onMessage = require('./on_message') 5 | const onDisconnect = require('./on_disconnect') 6 | const send = require('../../wss/send') 7 | const getAllAOs = require('../cmds/get_all_aos') 8 | 9 | module.exports = (asState, ws) => { 10 | debug('ws client connected') 11 | 12 | ws.on('message', msg => onMessage(asState, ws, msg)) 13 | ws.on('close', () => onDisconnect(ws)) 14 | 15 | send(ws, ['connected']) 16 | getAllAOs(asState, ws) 17 | } 18 | -------------------------------------------------------------------------------- /docs/ws_api.md: -------------------------------------------------------------------------------- 1 | ### WebSocket API 2 | 3 | The following commands can be sent to a running `bfx-hf-algo-server` instance: 4 | 5 | * `['get.aos']` - request a `data.aos` packet (see below) 6 | * `['submit.ao', type, params]` - start a new algo order with the specified parameters 7 | * `['stop.ao', gid]` - stop a running algo order by GID 8 | 9 | The response to `get.aos` has the following format: 10 | ```js 11 | ['data.aos', [[ 12 | gid, 13 | algoID, // i.e. 'bfx-iceberg' 14 | active, 15 | state, // current execution state (contains execution parameters) 16 | mtsCreated 17 | ], [ 18 | // ... 19 | ]]] 20 | ``` 21 | -------------------------------------------------------------------------------- /lib/wss/events/on_message.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const _isFunction = require('lodash/isFunction') 4 | const debug = require('debug')('bfx:hf:algo-server:wss:events:on-message') 5 | const getAllAOs = require('../cmds/get_all_aos') 6 | const submitAO = require('../cmds/submit_ao') 7 | const stopAO = require('../cmds/stop_ao') 8 | 9 | const cmdMap = { 10 | 'get.aos': getAllAOs, 11 | 'submit.ao': submitAO, 12 | 'stop.ao': stopAO 13 | } 14 | 15 | module.exports = async (asState, ws, msgJSON = '') => { 16 | let msg 17 | 18 | try { 19 | msg = JSON.parse(msgJSON) 20 | } catch (e) { 21 | debug('error reading ws client msg: %s', msgJSON) 22 | } 23 | 24 | if (!Array.isArray(msg)) { 25 | debug('ws client msg not an array: %j', msg) 26 | return 27 | } 28 | 29 | const [cmd] = msg 30 | const handler = cmdMap[cmd] 31 | 32 | if (!_isFunction(handler)) { 33 | debug('received unknown command: %s', cmd) 34 | return 35 | } 36 | 37 | return handler(asState, ws, msg) 38 | } 39 | -------------------------------------------------------------------------------- /examples/submit_ao_ws.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | process.env.DEBUG = 'bfx:*' 4 | 5 | const WebSocket = require('ws') 6 | const debug = require('debug')('bfx:hf:algo-server:examples:submit-ws') 7 | 8 | const ws = new WebSocket('ws://localhost:8877') 9 | 10 | ws.on('open', () => { 11 | debug('socket opened') 12 | 13 | ws.send(JSON.stringify(['submit.ao', 'bfx-accumulate_distribute', { 14 | symbol: 'tBTCUSD', 15 | amount: -0.2, 16 | sliceAmount: -0.1, 17 | sliceInterval: 10000, 18 | intervalDistortion: 0.20, 19 | amountDistortion: 0.20, 20 | orderType: 'RELATIVE', 21 | offsetType: 'ask', 22 | offsetDelta: -10, 23 | capType: 'bid', 24 | capDelta: 10, 25 | submitDelay: 150, 26 | cancelDelay: 150, 27 | catchUp: true, 28 | awaitFill: true, 29 | _margin: false 30 | }])) 31 | }) 32 | 33 | ws.on('message', (msgJSON) => { 34 | debug('recv %s', msgJSON) 35 | 36 | let msg 37 | 38 | try { 39 | msg = JSON.parse(msgJSON) 40 | } catch (e) { 41 | debug('error parsing received JSON: %s', e.message) 42 | } 43 | 44 | debug('recv %j', msg) 45 | }) 46 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | # 1.4.3 2 | - fix: when initiating a new server instance, correctly use the passed in host 3 | 4 | # 1.4.2 5 | - meta: bump bitfinex-api-node to v4 6 | 7 | # 1.4.1 8 | - docs: create/update 9 | 10 | # 1.4.0 11 | - refactor: manual open() call now required to start ws server 12 | - refactor: moved heartbeat responsibility into AO adapter 13 | - manifest: bump deps 14 | - meta: add github issue/pr templates 15 | - meta: standardize travis config 16 | - meta: add placeholder npm test 17 | - meta: updated readme 18 | - meta: removed scripts, cannot predict DB backend 19 | - fix: AOHost instance now connects in sync with the internal wss server 20 | 21 | # 1.3.0 22 | - refactor: use new AO adapter system (now requires exchange adapter plugin) 23 | - refactor: use AO gid for creation timestamp 24 | - feature: add stop AO command to server 25 | - fix: standard --fix 26 | 27 | # 1.2.1 28 | - fix: deregister listeners in clearAlgoHost() 29 | - manifest: bump deps 30 | 31 | # 1.2.0 32 | - refactor: finalize bfx-hf-models migration 33 | - feature: add clear AOs script 34 | - feature: add ability to change AO Host to server 35 | - manifest: bump deps 36 | 37 | # 1.1.2 38 | - refactor: pass local DB instance to AOHost (revert) 39 | 40 | # 1.1.1 41 | - was WIP bump prior to 1.2.0 42 | 43 | # 1.1.0 44 | - manifest: bump bfx-hf-algo 45 | - feature: set full AO set on startup 46 | - refactor: update AO IDs due to bfx-hf-algo bump 47 | - refactor: use bfx-hf-algo DB instance 48 | 49 | # 1.0.4 50 | - fix: update bfx-hf-algo import naming 51 | 52 | # 1.0.3 53 | - feature: add scripts to list, start an stop orders 54 | - feature: add API commands for listing & submitting AOs 55 | - feature: add close method to server 56 | - fix: export server in index.js 57 | - meta: add LICENSE 58 | 59 | # 1.0.2 60 | - fix: delay manager init to allow AO UI defs to register 61 | - fix: catch ws send() errors due to closed connection 62 | 63 | # 1.0.1 64 | - feature: include Ping/Pong in default server AO set 65 | - meta: update readme 66 | - meta: rm package-lock.json 67 | - fix: standard --fix 68 | 69 | # 1.0.0 70 | - Initial version 71 | 72 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bfx-hf-algo-server", 3 | "version": "1.4.4", 4 | "description": "HF Algorithmic Order Server", 5 | "main": "index.js", 6 | "engines": { 7 | "node": ">=7" 8 | }, 9 | "directories": { 10 | "lib": "lib" 11 | }, 12 | "author": "Bitfinex", 13 | "contributors": [ 14 | "Cris Mihalache (https://www.bitfinex.com)", 15 | "Paolo Ardoino (https://www.bitfinex.com)", 16 | "Jacob Plaster (https://www.bitfinex.com)", 17 | "Anton Nazarenko " 18 | ], 19 | "license": "Apache-2.0", 20 | "scripts": { 21 | "lint": "standard", 22 | "test": "npm run lint && npm run unit", 23 | "unit": "NODE_ENV=test mocha -R spec -b --recursive", 24 | "start": "node examples/server.js", 25 | "server_docs": "node_modules/jsdoc-to-markdown/bin/cli.js lib/server.js > docs/server.md", 26 | "docs": "npm run server_docs" 27 | }, 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/bitfinexcom/bfx-hf-algo-server.git" 31 | }, 32 | "bugs": { 33 | "url": "https://github.com/bitfinexcom/bfx-hf-algo-server/issues" 34 | }, 35 | "keywords": [ 36 | "honey framework", 37 | "bitfinex", 38 | "bitcoin", 39 | "BTC" 40 | ], 41 | "dependencies": { 42 | "bfx-hf-algo": "git+https://github.com/bitfinexcom/bfx-hf-algo.git#v2.0.0", 43 | "bfx-hf-models": "git+https://github.com/bitfinexcom/bfx-hf-models.git#v2.1.0", 44 | "bfx-hf-util": "git+https://github.com/bitfinexcom/bfx-hf-util.git#v1.0.1", 45 | "debug": "^4.2.0", 46 | "dotenv": "^6.0.0", 47 | "lodash": "^4.17.10", 48 | "ws": "^7.3.1" 49 | }, 50 | "devDependencies": { 51 | "bfx-api-node-rest": "^1.1.4", 52 | "bfx-hf-ext-plugin-bitfinex": "git+https://github.com/bitfinexcom/bfx-hf-ext-plugin-bitfinex.git#v1.0.0", 53 | "bfx-hf-models-adapter-lowdb": "git+https://github.com/bitfinexcom/bfx-hf-models-adapter-lowdb.git#v1.0.0", 54 | "jsdoc-to-markdown": "^5.0.1", 55 | "mocha": "^6.2.0", 56 | "socks-proxy-agent": "^4.0.1", 57 | "standard": "^14.2.0" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /docs/server.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## AlgoServer 4 | Honey Framework Algorithmic Order Server 5 | 6 | **Kind**: global class 7 | 8 | * [AlgoServer](#AlgoServer) 9 | * [new AlgoServer(args)](#new_AlgoServer_new) 10 | * [.open()](#AlgoServer+open) 11 | * [.close()](#AlgoServer+close) 12 | * [.clearAlgoHost()](#AlgoServer+clearAlgoHost) 13 | * [.setAlgoHost(aoHost)](#AlgoServer+setAlgoHost) 14 | 15 | 16 | 17 | ### new AlgoServer(args) 18 | 19 | | Param | Type | Description | 20 | | --- | --- | --- | 21 | | args | Object | passed to internal AO host | 22 | | args.db | Object | bfx-hf-models DB instance | 23 | | args.adapter | AOAdapter | exchange API adapter instance | 24 | | args.aos | Array.<Object> | algorithmic order definitions | 25 | | args.port | number | websocket server port | 26 | 27 | 28 | 29 | ### algoServer.open() 30 | Starts the WebSocket API server and opens the exchange connection. 31 | If the API server has already been started, an error is thrown. 32 | 33 | **Kind**: instance method of [AlgoServer](#AlgoServer) 34 | 35 | 36 | ### algoServer.close() 37 | Closes both the WebSocket API server and the exchange connection. 38 | If the API server is already closed, an error is thrown. 39 | 40 | **Kind**: instance method of [AlgoServer](#AlgoServer) 41 | 42 | 43 | ### algoServer.clearAlgoHost() 44 | Removes all of the event bindings from the current established algo host 45 | before calling for the algo host object to be closed. If there is no host 46 | established then this function is a no-op. 47 | 48 | **Kind**: instance method of [AlgoServer](#AlgoServer) 49 | 50 | 51 | ### algoServer.setAlgoHost(aoHost) 52 | Sets the event bindings to use the given algo host instance. This function 53 | also manages the closing of the old host instance and the establishment of 54 | the new host instance. 55 | 56 | If the WebSocket API server is running, the exchange connection is opened. 57 | 58 | **Kind**: instance method of [AlgoServer](#AlgoServer) 59 | 60 | | Param | Type | 61 | | --- | --- | 62 | | aoHost | Object | 63 | 64 | -------------------------------------------------------------------------------- /examples/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | process.env.DEBUG = '*' // 'bfx:hf:*' 4 | 5 | require('dotenv').config() 6 | require('bfx-hf-util/lib/catch_uncaught_errors') 7 | 8 | const debug = require('debug')('bfx:hf:algo-server:examples:server') 9 | const SocksProxyAgent = require('socks-proxy-agent') 10 | const _isFunction = require('lodash/isFunction') 11 | const { 12 | PingPong, Iceberg, TWAP, AccumulateDistribute, MACrossover 13 | } = require('bfx-hf-algo') 14 | 15 | const { version: VERSION } = require('../package.json') 16 | const { RESTv2 } = require('bfx-api-node-rest') 17 | const HFDB = require('bfx-hf-models') 18 | const HFDBLowDBAdapter = require('bfx-hf-models-adapter-lowdb') 19 | const { 20 | AOAdapter: BFXAOAdapter, 21 | schema: HFDBBitfinexSchema 22 | } = require('bfx-hf-ext-plugin-bitfinex') 23 | 24 | const AOServer = require('../lib/server') 25 | const { 26 | API_KEY, API_SECRET, WS_URL, REST_URL, SOCKS_PROXY_URL, DB_FILENAME, 27 | PLATFORM = 'bitfinex' 28 | } = process.env 29 | 30 | const AO_SETTINGS_KEY = `api:${PLATFORM}_algorithmic_orders` 31 | const algoOrders = [ 32 | PingPong, Iceberg, TWAP, AccumulateDistribute, MACrossover 33 | ] 34 | 35 | // init db 36 | const db = new HFDB({ 37 | schema: HFDBBitfinexSchema, 38 | adapter: HFDBLowDBAdapter({ 39 | dbPath: `${__dirname}/../${DB_FILENAME}`, 40 | schema: HFDBBitfinexSchema 41 | }) 42 | }) 43 | 44 | // init algo order adapter 45 | const adapter = new BFXAOAdapter({ 46 | apiKey: API_KEY, 47 | apiSecret: API_SECRET, 48 | wsURL: WS_URL, 49 | restURL: REST_URL, 50 | agent: SOCKS_PROXY_URL ? new SocksProxyAgent(SOCKS_PROXY_URL) : null, 51 | withHeartbeat: true, 52 | dms: 4 53 | }) 54 | 55 | // init algo order server 56 | const server = new AOServer({ 57 | db, 58 | adapter, 59 | port: 8877, 60 | aos: algoOrders 61 | }) 62 | 63 | server.on('auth:success', () => { 64 | debug('authenticated') 65 | }) 66 | 67 | server.on('auth:error', (error) => { 68 | debug('auth error: %j', error) 69 | }) 70 | 71 | // register algo order UI definitions 72 | const aoUIDefs = algoOrders.filter((ao) => { 73 | const { meta = {} } = ao 74 | const { getUIDef } = meta 75 | 76 | return _isFunction(getUIDef) 77 | }).map((ao) => { 78 | const { meta = {} } = ao 79 | const { getUIDef } = meta 80 | const { id } = ao 81 | 82 | return { 83 | id, 84 | uiDef: getUIDef({ 85 | timeframes: Object.values(BFXAOAdapter.getTimeFrames()) 86 | }) 87 | } 88 | }) 89 | 90 | const rest = new RESTv2({ 91 | apiKey: API_KEY, 92 | apiSecret: API_SECRET, 93 | url: REST_URL 94 | }) 95 | 96 | const run = async () => { 97 | debug('starting algo server version %s', VERSION) 98 | 99 | const res = await rest.getSettings([AO_SETTINGS_KEY]) 100 | const [keyResult = []] = res 101 | const [, aoSettings = {}] = keyResult 102 | 103 | aoUIDefs.forEach(({ id, uiDef }) => { 104 | debug('setting UI def for %s', id) 105 | aoSettings[id] = uiDef 106 | }) 107 | 108 | await rest.updateSettings({ [AO_SETTINGS_KEY]: aoSettings }) 109 | 110 | debug('all UIs registered!') 111 | 112 | // start server 113 | server.open() 114 | } 115 | 116 | try { 117 | run() 118 | } catch (e) { 119 | debug('error: %s', e.stack) 120 | } 121 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Bitfinex Honey Framework Algorithmic Order Server for Node.JS 2 | 3 | [![Build Status](https://travis-ci.org/bitfinexcom/bfx-hf-algo-server.svg?branch=master)](https://travis-ci.org/bitfinexcom/bfx-hf-algo-server) 4 | 5 | This is a thin wrapper around the [`bfx-hf-algo`](https://github.com/bitfinexcom/bfx-hf-algo) `AOHost` class, which connects it to the Bitfinex notification system in order to start algo orders from the order form in the bfx UI. The AOHost automatically uploads all relevant order form layouts on startup. 6 | 7 | The algo orders themselves are implemented in [`bfx-hf-algo`](https://github.com/bitfinexcom/bfx-hf-algo). 8 | 9 | Algo orders are automatically persisted via a DB backend provided by the user, and are resumed when the algo server starts up. 10 | 11 | ### Features 12 | 13 | * Enables the execution of algorithmic orders via the official Bitfinex UI 14 | * Exposes a WebSocket API for executing & managing the operation of algo orders 15 | * Allows for the usage of custom DB backends via the `bfx-hf-models` system 16 | 17 | ### Installation 18 | 19 | For standalone usage: 20 | ```bash 21 | git clone https://github.com/bitfinexcom/bfx-hf-algo-server 22 | cd bfx-hf-algo-server 23 | npm i 24 | 25 | touch .env 26 | 27 | echo 'DB_FILENAME=db/algo-server-db.json' >> .env 28 | echo 'API_KEY=...' >> .env 29 | echo 'API_SECRET=...' >> .env 30 | 31 | npm start 32 | ``` 33 | 34 | For usage/extension within an existing project: 35 | ```bash 36 | npm i --save bfx-hf-algo-server 37 | ``` 38 | 39 | ### Quickstart 40 | 41 | By default, the `lowdb` DB backend is used. To run the standard server, populate `.env` with your API credentials and DB path: 42 | ``` 43 | API_KEY=... 44 | API_SECRET=... 45 | DB_FILENAME=... 46 | ``` 47 | 48 | Then run `npm start` 49 | 50 | Refresh your Bitfinex UI after all order form layouts have been uploaded. Once the server is listening, select an algorithmic order from the order form dropdown and fill in your desired arguments. 51 | 52 | To start an algo order click the 'Submit' button in the Bitfinex UI to generate a broadcast notification which will be picked up by your running algo server instance, starting the desired order. 53 | 54 | The server can be stopped/started at will, with running algo orders automatically resuming if the contents of `db/*` have not been cleared. 55 | 56 | ### Docs 57 | 58 | [Refer to `docs/server.md`](/docs/server.md) for JSDoc-generated API documentation. For documentation on the available WebSocket API commands, [see `docs/ws_api.md`](/docs/ws_api.md). 59 | 60 | [See the `examples/`](/examples) folder for executable examples. 61 | 62 | ### Example 63 | 64 | ```js 65 | const { 66 | IcebergOrder, TWAPOrder, AccumulateDistribute, MACrossover 67 | } = require('bfx-hf-algo') 68 | 69 | const WebSocket = require('ws') 70 | const AOServer = require('bfx-hf-algo-server') 71 | const HFDB = require('bfx-hf-models') 72 | const HFDBLowDBAdapter = require('bfx-hf-models-adapter-lowdb') 73 | const { 74 | AOAdapter: BFXAOAdapter, schema: HFDBBitfinexSchema 75 | } = require('bfx-hf-ext-plugin-bitfinex') 76 | 77 | const DB_PATH = './some_path/db.json' 78 | 79 | // create database instance for persisting algo orders 80 | const db = new HFDB({ 81 | schema: HFDBBitfinexSchema, 82 | adapter: HFDBLowDBAdapter({ 83 | dbPath: DB_PATH, 84 | schema: HFDBBitfinexSchema 85 | }) 86 | }) 87 | 88 | // create exchange adapter for order execution 89 | const adapter = new BFXAOAdapter({ 90 | apiKey: '...', 91 | apiSecret: '...' 92 | }) 93 | 94 | // spawn algo server instance 95 | const server = new AOServer({ 96 | db, 97 | adapter, 98 | port: 8877, 99 | aos: [ 100 | PingPong, 101 | Iceberg, 102 | TWAP, 103 | AccumulateDistribute, 104 | MACrossover 105 | ] 106 | }) 107 | 108 | server.on('auth:success', () => { /* ... */ }) 109 | server.on('auth:error', (error) => { /* ... */ }) 110 | 111 | // ao server now ready to accept orders on port 8877 112 | // example order submit 113 | 114 | const ws = new WebSocket('ws://localhost:8877') 115 | 116 | ws.on('open', () => { 117 | ws.send(JSON.stringify(['submit.ao', 'bfx-accumulate_distribute', { 118 | symbol: 'tEOSUSD', 119 | amount: 10, 120 | sliceAmount: 1, 121 | sliceInterval: 5 * 1000, 122 | intervalDistortion: 0.20, 123 | amountDistortion: 0.20, 124 | orderType: 'MARKET', 125 | submitDelay: 150, 126 | cancelDelay: 150, 127 | catchUp: true, 128 | awaitFill: true, 129 | _margin: true 130 | }])) 131 | }) 132 | ``` 133 | 134 | ### Contributing 135 | 136 | 1. Fork it 137 | 2. Create your feature branch (`git checkout -b my-new-feature`) 138 | 3. Commit your changes (`git commit -am 'Add some feature'`) 139 | 4. Push to the branch (`git push origin my-new-feature`) 140 | 5. Create a new Pull Request 141 | -------------------------------------------------------------------------------- /lib/server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const { EventEmitter } = require('events') 4 | const { AOHost } = require('bfx-hf-algo') 5 | const _isObject = require('lodash/isObject') 6 | const _isFunction = require('lodash/isFunction') 7 | const _last = require('lodash/last') 8 | const debug = require('debug')('bfx:hf:algo-server:server') 9 | 10 | const startWSS = require('./wss/start_wss') 11 | const notifyResError = require('./ws/notify_res_error') 12 | const notifyRes = require('./ws/notify_res') 13 | 14 | /** 15 | * Honey Framework Algorithmic Order Server 16 | */ 17 | class AlgoServer extends EventEmitter { 18 | /** 19 | * @param {Object} args - passed to internal AO host 20 | * @param {Object} args.db - bfx-hf-models DB instance 21 | * @param {AOAdapter} args.adapter - exchange API adapter instance 22 | * @param {Object[]} args.aos - algorithmic order definitions 23 | * @param {number} args.port - websocket server port 24 | */ 25 | constructor (args = {}) { 26 | super() 27 | 28 | this.onAOStart = this.onAOStart.bind(this) 29 | this.onAOStop = this.onAOStop.bind(this) 30 | this.onWSNotification = this.onWSNotification.bind(this) 31 | this.onWSAuthError = this.onWSAuthError.bind(this) 32 | this.onWSAuthSuccess = this.onWSAuthSuccess.bind(this) 33 | this.onError = this.onError.bind(this) 34 | 35 | const { aos, port, db, adapter, host } = args 36 | 37 | this.db = db 38 | this.port = port 39 | this.adapter = adapter 40 | 41 | // If provided with order definitions then create the algoHost instance 42 | // Mostly just for backwards compatibility 43 | if (aos && !host) { 44 | const aoh = new AOHost({ aos, db, adapter }) 45 | this.setAlgoHost(aoh) 46 | } 47 | 48 | if (host) { 49 | this.setAlgoHost(host) 50 | } 51 | } 52 | 53 | /** 54 | * Starts the WebSocket API server and opens the exchange connection. 55 | * If the API server has already been started, an error is thrown. 56 | */ 57 | open () { 58 | if (this.wss) { 59 | throw new Error('already open') 60 | } 61 | 62 | this.wss = startWSS(this) 63 | 64 | if (this.host) { 65 | this.host.connect() 66 | } 67 | } 68 | 69 | /** 70 | * Closes both the WebSocket API server and the exchange connection. 71 | * If the API server is already closed, an error is thrown. 72 | */ 73 | close () { 74 | if (!this.wss) { 75 | throw new Error('already closed') 76 | } 77 | 78 | if (this.host) { 79 | this.host.close() 80 | } 81 | 82 | this.wss.close() 83 | this.wss = null 84 | } 85 | 86 | /** 87 | * Removes all of the event bindings from the current established algo host 88 | * before calling for the algo host object to be closed. If there is no host 89 | * established then this function is a no-op. 90 | */ 91 | clearAlgoHost () { 92 | if (this.host) { 93 | // remove all events from old host 94 | Object 95 | .keys(this.host.listeners) 96 | .forEach(eventName => this.host.removeAllListeners(eventName)) 97 | 98 | // close connection of old host 99 | this.host.close() 100 | } 101 | } 102 | 103 | /** 104 | * Sets the event bindings to use the given algo host instance. This function 105 | * also manages the closing of the old host instance and the establishment of 106 | * the new host instance. 107 | * 108 | * If the WebSocket API server is running, the exchange connection is opened. 109 | * 110 | * @param {Object} aoHost 111 | */ 112 | setAlgoHost (aoHost) { 113 | this.clearAlgoHost() 114 | this.host = aoHost 115 | 116 | // bind new events to new algo host 117 | this.host.on('ao:start', this.onAOStart) 118 | this.host.on('ao:stop', this.onAOStop) 119 | this.host.on('notification', this.onWSNotification) 120 | this.host.on('auth:error', this.onWSAuthError) 121 | this.host.on('auth:success', this.onWSAuthSuccess) 122 | this.host.on('error', this.onError) 123 | 124 | if (this.wss) { 125 | this.host.connect() 126 | } 127 | } 128 | 129 | /** 130 | * @param {Object} instance - algo order instance 131 | * @private 132 | */ 133 | onAOStart (instance) { 134 | const { state = {} } = instance 135 | const { id, gid } = state 136 | 137 | debug('started AO %s [gid %s]', id, gid) 138 | this.emit('ao:start', instance) 139 | } 140 | 141 | /** 142 | * @param {Object} instance - algo order instance 143 | * @private 144 | */ 145 | onAOStop (instance) { 146 | const { state = {} } = instance 147 | const { id, gid } = state 148 | 149 | debug('stopped AO %s [gid %s]', id, gid) 150 | this.emit('ao:stop', instance) 151 | } 152 | 153 | /** 154 | * @param {Error|string} err 155 | * @private 156 | */ 157 | onWSAuthError (err) { 158 | this.onError(err) 159 | } 160 | 161 | /** 162 | * @param {Object} data 163 | * @private 164 | */ 165 | onWSAuthSuccess (data) { 166 | debug('authenticated') 167 | this.emit('auth:success', data) 168 | } 169 | 170 | /** 171 | * @param {Error|string} err 172 | * @private 173 | */ 174 | onError (err) { 175 | debug('error: %s', _isObject(err) ? err.message : err) 176 | this.emit('error', _isObject(err) ? err : new Error(err)) 177 | } 178 | 179 | /** 180 | * @param {Object} packet - notification data 181 | * @private 182 | */ 183 | async onWSNotification (packet = {}) { 184 | const { type, messageID, notifyInfo = {} } = packet 185 | const splitType = type.split('-') 186 | const req = splitType.splice(splitType.length - 1, 1)[0] 187 | const [ucm, nType, ...idContents] = splitType 188 | 189 | // no algo host established 190 | if (!this.host) { 191 | return 192 | } 193 | 194 | if (_last(idContents) === 'res') { // ignore responses 195 | return 196 | } 197 | 198 | const id = idContents.join('-') 199 | 200 | if (ucm !== 'ucm' || req !== 'req') { 201 | return 202 | } 203 | if (nType === 'preview') { 204 | debug('recv preview for %s', id) 205 | this.onPreview(id, messageID, type, notifyInfo) 206 | } else if (nType === 'submit') { 207 | debug('recv submit for %s', id) 208 | await this.onSubmit(id, messageID, type, notifyInfo) 209 | } 210 | } 211 | 212 | /** 213 | * Like @onSubmit, but generates a set of preview orders and sends them via 214 | * the exchange connection to be displayed to the user on success. 215 | * 216 | * @param {string} id - algo order ID 217 | * @param {number} mid - incoming notification ID, used to generate response ID 218 | * @param {string} type - incoming notification type, replicated on outgoing success/error notification 219 | * @param {Object} payload - algo order parameters 220 | * @private 221 | */ 222 | onPreview (id, mid, type, payload) { 223 | const ao = this.host.getAO(id) 224 | 225 | if (!ao) { 226 | return this.onError(new Error(`preview requested for unknown AO: ${id}`)) 227 | } 228 | 229 | const { meta = {} } = ao 230 | const { validateParams, processParams, genPreview } = meta 231 | 232 | const params = _isFunction(processParams) 233 | ? processParams(payload) 234 | : { ...payload } 235 | 236 | if (_isFunction(validateParams)) { 237 | const err = validateParams(params) 238 | 239 | if (err) { 240 | notifyResError(this, mid, type, err) 241 | debug('error in preview request: %s', err) 242 | return 243 | } 244 | } 245 | 246 | if (!_isFunction(genPreview)) { 247 | debug('requested preview for AO with no genPreview method: %s', id) 248 | return 249 | } 250 | 251 | const orders = genPreview(params) 252 | 253 | notifyRes(this, mid, type, { 254 | orders: orders.map(o => { 255 | return typeof o.toPreview === 'function' 256 | ? o.toPreview() 257 | : o 258 | }), 259 | 260 | notify: { 261 | level: 'info', 262 | message: `Generated ${orders.filter(o => !o.label).length} preview orders` 263 | } 264 | }) 265 | } 266 | 267 | /** 268 | * Attempts to start the specified algo order with the provided parameters. 269 | * In case of failure (i.e. invalid paramters) an error notification is 270 | * passed to the internal host and propagated to the exchange connection. If 271 | * successfull, a similar notification is passed to the exchange connection. 272 | * 273 | * @param {string} id - algo order ID 274 | * @param {number} mid - incoming notification ID, used to generate response ID 275 | * @param {string} type - incoming notification type, replicated on outgoing success/error notification 276 | * @param {Object} payload - algo order parameters 277 | * @private 278 | */ 279 | async onSubmit (id, mid, type, payload) { 280 | const ao = this.host.getAO(id) 281 | 282 | if (!ao) { 283 | return this.onError(new Error(`submit requested for unknown AO: ${id}`)) 284 | } 285 | 286 | const { meta = {} } = ao 287 | const { validateParams, processParams } = meta 288 | 289 | const params = _isFunction(processParams) 290 | ? processParams(payload) 291 | : { ...payload } 292 | 293 | if (_isFunction(validateParams)) { 294 | const err = validateParams(params) 295 | 296 | if (err) { 297 | notifyResError(this, mid, type, err) 298 | debug('error in submit request: %s', err) 299 | return 300 | } 301 | } 302 | 303 | try { 304 | await this.host.startAO(id, payload) 305 | notifyRes(this, mid, type, { 306 | notify: { 307 | level: 'success', 308 | message: `Started ${ao.name} order` 309 | } 310 | }) 311 | } catch (err) { 312 | notifyResError(this, mid, type, 'Internal AO Server Error') 313 | debug('error starting AO: %s', err.stack) 314 | } 315 | } 316 | } 317 | 318 | module.exports = AlgoServer 319 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------