ctubio / tribeca

Self-hosted crypto trading bot (automated high frequency market making) in node.js, angular, typescript and c++
https://127.0.0.1:3000
Other
95 stars 26 forks source link

Okccoin.cn does not work. Cannot read property 'funds' of undefined" error #bug #9

Closed Bzzz666 closed 7 years ago

Bzzz666 commented 7 years ago
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-17T02:29:16.751Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-17T02:29:17.060Z","v":0}
{"name":"tribeca:active","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-17T02:29:17.352Z","v":0}
{"name":"ewma","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-17T02:29:17.378Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:283:41)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-17T02:29:19.120Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"persisting active to true","time":"2017-01-17T02:29:19.123Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-17T02:29:19.136Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-17T02:29:19.138Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":15,"level":30,"msg":"Exiting with code 0","time":"2017-01-17T02:29:19.139Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt #1
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-17T02:29:21.775Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-17T02:29:22.100Z","v":0}
{"name":"tribeca:active","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-17T02:29:22.400Z","v":0}
{"name":"ewma","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-17T02:29:22.428Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:283:41)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-17T02:29:23.477Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"persisting active to true","time":"2017-01-17T02:29:23.480Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-17T02:29:23.493Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-17T02:29:23.495Z","v":0}
{"name":"tribeca:main","hostname":"bbff2c3d3707","pid":25,"level":30,"msg":"Exiting with code 0","time":"2017-01-17T02:29:23.497Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt `#2` 
ctubio commented 7 years ago

i will need to open an account in this exchange for test, will do somewhat soon many thanks for the report!

ctubio commented 7 years ago

Im sorry for me OkCoin is working fine, i just set OkCoinApiKey and OkCoinSecretKey values and restart tribeca in last version.

Maybe you know in what special situation this error occurs? On a fresh account with balanace on BTC and trading USD/BTC this error does not seems to occur :sob:, this is my output:

$ nodejs tribeca.js
{"name":"tribeca:main","hostname":"mailbox","pid":3829,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-17T19:15:26.274Z","v":0}
{"name":"tribeca:main","hostname":"mailbox","pid":3829,"level":30,"msg":"Listening to admins on *: 9333","time":"2017-01-17T19:15:26.351Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":3829,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-17T19:15:26.433Z","v":0}
{"name":"ewma","hostname":"mailbox","pid":3829,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-17T19:15:26.441Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":3829,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-17T19:15:27.528Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":3829,"level":30,"msg":"Successfully connected to ok_usd_realtrades","time":"2017-01-17T19:15:27.763Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":3829,"level":30,"msg":"Successfully connected to ok_btcusd_depth","time":"2017-01-17T19:15:27.764Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":3829,"level":30,"msg":"Successfully connected to ok_btcusd_trades_v1","time":"2017-01-17T19:15:27.768Z","v":0}
{"name":"positionmanager","hostname":"mailbox","pid":3829,"level":30,"msg":"recalculated target base position: 1","time":"2017-01-17T19:15:41.715Z","v":0}

But while it was trading, i found OkCoin seems to not keep orders opened, it just cancels as soon as it creates. Maybe is not a good idea to use OkCoin with tribeca in the current state of okcoin gateway in tribeca :sob:

Bzzz666 commented 7 years ago

tried with fullfilled account, same... (last version)

error: Script restart attempt #14
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-17T20:21:44.287Z","v":0}
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-17T20:21:44.514Z","v":0}
{"name":"tribeca:active","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-17T20:21:44.742Z","v":0}
{"name":"ewma","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-17T20:21:44.763Z","v":0}
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:283:41)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-17T20:21:45.154Z","v":0}
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"persisting active to true","time":"2017-01-17T20:21:45.157Z","v":0}
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-17T20:21:45.174Z","v":0}
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-17T20:21:45.176Z","v":0}
{"name":"tribeca:main","hostname":"8e5ef89f4fb5","pid":155,"level":30,"msg":"Exiting with code 0","time":"2017-01-17T20:21:45.178Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt #15

can you share your config example?

ctubio commented 7 years ago

i created in okcoin a new API Key only checked with permissions for trade, then my configs was like:

{
    "TRIBECA_MODE": "prod",
    "EXCHANGE": "okcoin",
    "TradedPair": "BTC/USD",
    "MongoDbUrl": "mongodb://localhost:27017/tribeca",
    "WebClientUsername": "whatever",
    "WebClientPassword": "whatever",
    "WebClientListenPort": "6969",

    "HitBtcPullUrl": "http://api.hitbtc.com",
    "HitBtcOrderEntryUrl": "wss://api.hitbtc.com:8080",
    "HitBtcMarketDataUrl": "ws://api.hitbtc.com:80",
    "HitBtcSocketIoUrl": "https://api.hitbtc.com:8081",
    "HitBtcApiKey": "NULL",
    "HitBtcSecret": "NULL",
    "HitBtcOrderDestination": "HitBtc",

    "CoinbaseRestUrl": "https://api.gdax.com",
    "CoinbaseWebsocketUrl": "wss://ws-feed.gdax.com",
    "CoinbasePassphrase": "whatever",
    "CoinbaseApiKey": "whatever",
    "CoinbaseSecret": "whatever",
    "CoinbaseOrderDestination": "Coinbase",

    "OkCoinWsUrl": "wss://real.okcoin.com:10440/websocket/okcoinapi",
    "OkCoinHttpUrl": "https://www.okcoin.com/api/v1/",
    "OkCoinApiKey": "whatever",
    "OkCoinSecretKey": "whatever",
    "OkCoinOrderDestination": "OkCoin",

    "BitfinexHttpUrl": "https://api.bitfinex.com/v1",
    "BitfinexKey": "NULL",
    "BitfinexSecret": "NULL",
    "BitfinexOrderDestination": "Bitfinex"
}

you may need to replace the whatever values, but the urls are tested to be working as expected, at least in my tests. im not sure what is your difference :sob: maybe you can try creating a new API Key?

mmm.. if you agree, i can create a branch with some debug lines, that you can run and paste back here (removing sensitive information if any), maybe it helps to make a patch for your situation.

Bzzz666 commented 7 years ago

Yes, it will be nice.

ctubio commented 7 years ago

I just created the branch patch-okcoin-funds-typeerror, the expected output is like:

$ nodejs  tribeca.js
{"name":"tribeca:main","hostname":"mailbox","pid":8474,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-17T23:18:27.978Z","v":0}
{"name":"tribeca:main","hostname":"mailbox","pid":8474,"level":30,"msg":"Listening to admins on *: 9333","time":"2017-01-17T23:18:28.062Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":8474,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-17T23:18:28.158Z","v":0}
{"name":"ewma","hostname":"mailbox","pid":8474,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-17T23:18:28.165Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"typeof msg object","time":"2017-01-17T23:18:29.249Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"msg Timestamped {\n  data: { info: { funds: [Object] }, result: true },\n  time: moment.utc(\"2017-01-17T23:18:29.249+00:00\") }","time":"2017-01-17T23:18:29.253Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"typeof msgData object","time":"2017-01-17T23:18:29.253Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"msgData { info: { funds: { asset: [Object], free: [Object], freezed: [Object] } },\n  result: true }","time":"2017-01-17T23:18:29.253Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"typeof msgDataInfo object","time":"2017-01-17T23:18:29.253Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"msgDataInfo { funds: \n   { asset: { net: '90.53', total: '90.53' },\n     free: { btc: '0.1', ltc: '0', usd: '0' },\n     freezed: { btc: '0', ltc: '0', usd: '0' } } }","time":"2017-01-17T23:18:29.254Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"typeof msgDataInfoFunds object","time":"2017-01-17T23:18:29.254Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"mailbox","pid":8474,"level":30,"msg":"msgDataInfoFunds { asset: { net: '90.53', total: '90.53' },\n  free: { btc: '0.1', ltc: '0', usd: '0' },\n  freezed: { btc: '0', ltc: '0', usd: '0' } }","time":"2017-01-17T23:18:29.254Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":8474,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-17T23:18:29.326Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":8474,"level":30,"msg":"Successfully connected to ok_usd_realtrades","time":"2017-01-17T23:18:29.551Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":8474,"level":30,"msg":"Successfully connected to ok_btcusd_depth","time":"2017-01-17T23:18:29.553Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":8474,"level":30,"msg":"Successfully connected to ok_btcusd_trades_v1","time":"2017-01-17T23:18:29.569Z","v":0}

can you please try it? thanks'¡

Bzzz666 commented 7 years ago
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-17T23:44:12.411Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Listening to admins on *: 6969","time":"2017-01-17T23:44:12.655Z","v":0}
{"name":"tribeca:active","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-17T23:44:12.911Z","v":0}
{"name":"ewma","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-17T23:44:12.934Z","v":0}
{"name":"tribeca:active","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-17T23:44:14.403Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"74ea7f3fa5ae","pid":15,"level":40,"msg":"Unsuccessful message { channel: 'ok_usd_realtrades',\n  errorcode: '10002',\n  success: 'false' }","time":"2017-01-17T23:44:14.714Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Successfully connected to ok_btcusd_depth","time":"2017-01-17T23:44:14.717Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Successfully connected to ok_btcusd_trades_v1","time":"2017-01-17T23:44:14.741Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Event looped blocked for 189.93ms","time":"2017-01-17T23:44:15.006Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"typeof msg object","time":"2017-01-17T23:44:15.053Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"msg Timestamped {\n  data: { errorCode: 10000, result: false },\n  time: moment.utc(\"2017-01-17T23:44:15.053+00:00\") }","time":"2017-01-17T23:44:15.061Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"typeof msgData object","time":"2017-01-17T23:44:15.061Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"msgData { errorCode: 10000, result: false }","time":"2017-01-17T23:44:15.062Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"typeof msgDataInfo undefined","time":"2017-01-17T23:44:15.063Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"msgDataInfo undefined","time":"2017-01-17T23:44:15.064Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:291:51)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-17T23:44:15.070Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"persisting active to true","time":"2017-01-17T23:44:15.073Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-17T23:44:15.083Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-17T23:44:15.086Z","v":0}
{"name":"tribeca:main","hostname":"74ea7f3fa5ae","pid":15,"level":30,"msg":"Exiting with code 0","time":"2017-01-17T23:44:15.088Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt #1
ctubio commented 7 years ago

mm.. seems like errors 10000 and 10002, based on https://www.okcoin.com/rest_request.html this means:

10000   Required field, can not be null
10002   System error

if you agree, please try again the branch patch-okcoin-funds-typeerror, i just added a new commit to print the msg send to okcoin; we can use this to discover what fields are missing, or you can use it to contact the support of okcoin if we dont see nothing wrong.

Since is working fine for me, i believe the app is correctly sending all the fields, so the problem may be in your account, but anyway lets output the payload of ok_usd_realtrades request.

The expected request is:

{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":10015,"level":30,"msg":"JSON payload ok_usd_realtrades {\"event\":\"addChannel\",\"channel\":\"ok_usd_realtrades\",\"parameters\":{\"api_key\":\"whatever\",\"sign\":\"whatever\"}}","time":"2017-01-18T00:34:29.040Z","v":0}

please remove the api_key and sign values before paste anywhere (even okcoin support team).

Note that the api_key must mach your key configured, but the sign is a generated value that is not configured anywhere.

Also check if you have the same value for the api key in the payload of your request and in your tribeca.json file please.

Bzzz666 commented 7 years ago

api_key - same sign - not same

docker logs tribeca-master
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-18T01:35:57.791Z","v":0}
{"name":"tribeca:active","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-18T01:35:58.089Z","v":0}
{"name":"ewma","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-18T01:35:58.112Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"99e9aa196365","pid":15,"level":30,"msg":"JSON payload ok_usd_realtrades {\"event\":\"addChannel\",\"channel\":\"ok_usd_realtrades\",\"parameters\":{\"api_key\":\"___was_a_key___\",\"sign\":\"____was_a_sign___\"}}","time":"2017-01-18T01:36:00.006Z","v":0}
{"name":"tribeca:active","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-18T01:36:00.014Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"99e9aa196365","pid":15,"level":40,"msg":"Unsuccessful message { channel: 'ok_usd_realtrades',\n  errorcode: '10002',\n  success: 'false' }","time":"2017-01-18T01:36:00.352Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Successfully connected to ok_btcusd_depth","time":"2017-01-18T01:36:00.355Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Successfully connected to ok_btcusd_trades_v1","time":"2017-01-18T01:36:00.379Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Event looped blocked for 205.6ms","time":"2017-01-18T01:36:00.568Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":15,"level":30,"msg":"typeof msg object","time":"2017-01-18T01:36:01.181Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":15,"level":30,"msg":"msg Timestamped {\n  data: { errorCode: 10000, result: false },\n  time: moment.utc(\"2017-01-18T01:36:01.181+00:00\") }","time":"2017-01-18T01:36:01.190Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":15,"level":30,"msg":"typeof msgData object","time":"2017-01-18T01:36:01.191Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":15,"level":30,"msg":"msgData { errorCode: 10000, result: false }","time":"2017-01-18T01:36:01.192Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":15,"level":30,"msg":"typeof msgDataInfo undefined","time":"2017-01-18T01:36:01.193Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":15,"level":30,"msg":"msgDataInfo undefined","time":"2017-01-18T01:36:01.194Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:293:51)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-18T01:36:01.199Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":30,"msg":"persisting active to true","time":"2017-01-18T01:36:01.203Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-18T01:36:01.212Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-18T01:36:01.218Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":15,"level":30,"msg":"Exiting with code 0","time":"2017-01-18T01:36:01.220Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt #1
{"name":"tribeca:main","hostname":"99e9aa196365","pid":25,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-18T01:36:03.943Z","v":0}
{"name":"tribeca:active","hostname":"99e9aa196365","pid":25,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-18T01:36:04.229Z","v":0}
{"name":"ewma","hostname":"99e9aa196365","pid":25,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-18T01:36:04.253Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":25,"level":30,"msg":"typeof msg object","time":"2017-01-18T01:36:05.498Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":25,"level":30,"msg":"msg Timestamped {\n  data: { errorCode: 10000, result: false },\n  time: moment.utc(\"2017-01-18T01:36:05.497+00:00\") }","time":"2017-01-18T01:36:05.506Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":25,"level":30,"msg":"typeof msgData object","time":"2017-01-18T01:36:05.507Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":25,"level":30,"msg":"msgData { errorCode: 10000, result: false }","time":"2017-01-18T01:36:05.509Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":25,"level":30,"msg":"typeof msgDataInfo undefined","time":"2017-01-18T01:36:05.510Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"99e9aa196365","pid":25,"level":30,"msg":"msgDataInfo undefined","time":"2017-01-18T01:36:05.511Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":25,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:293:51)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-18T01:36:05.518Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":25,"level":30,"msg":"persisting active to true","time":"2017-01-18T01:36:05.520Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":25,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-18T01:36:05.532Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":25,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-18T01:36:05.534Z","v":0}
{"name":"tribeca:main","hostname":"99e9aa196365","pid":25,"level":30,"msg":"Exiting with code 0","time":"2017-01-18T01:36:05.535Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt #2
ctubio commented 7 years ago

your request looks OK, same as my request. therefore i suggest to contact okcoin at support@okcoin.com with the following message:

Request:
{"event":"addChannel","channel":"ok_usd_realtrades","parameters":{"api_key":"___was_a_key___","sign":"____was_a_sign___"}}

Response:
 { channel: 'ok_usd_realtrades',  errorcode: '10002',  success: 'false' }

I belive they will fix something in your account, or let you know if something is wrong in your account, because we are sending correctly all the possible fields in the ok_usd_realtrades request (but in case we are not, please paste to their support team the request and the response removing sensitive values so they can investigate further the reason [we can't investigate more since your request looks equal than mine]).

Bzzz666 commented 7 years ago

I discovered what the problem was about. It turned out that two okcoin sites, okcoin.com(BTC\USD) and okcoin.cn(BTC\USD) I owe access keys from okcoin.cn, that's why it was not working.

When I trider to change API urls to okcoin.cn`s it errored with:

{"name":"tribeca:main","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-18T03:32:08.781Z","v":0}
{"name":"tribeca:active","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-18T03:32:09.048Z","v":0}
{"name":"ewma","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-18T03:32:09.071Z","v":0}
{"name":"tribeca:main","hostname":"scw-d786d3","pid":20473,"level":50,"err":{"message":"Unsupported currency cny","name":"Error","stack":"Error: Unsupported currency cny\n    at Function.convertCurrency (/home/tribeca/app/service/gateways/okcoin.js:306:28)\n    at _http.post.then.msg (/home/tribeca/app/service/gateways/okcoin.js:292:95)\n    at _fulfilled (/home/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/home/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/home/tribeca/node_modules/q/q.js:796:13)\n    at /home/tribeca/node_modules/q/q.js:604:44\n    at runSingle (/home/tribeca/node_modules/q/q.js:137:13)\n    at flush (/home/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-18T03:32:10.715Z","v":0}
{"name":"tribeca:main","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"persisting active to true","time":"2017-01-18T03:32:10.717Z","v":0}
{"name":"tribeca:main","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-18T03:32:10.727Z","v":0}
{"name":"tribeca:main","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-18T03:32:10.729Z","v":0}
{"name":"tribeca:main","hostname":"scw-d786d3","pid":20473,"level":30,"msg":"Exiting with code 0","time":"2017-01-18T03:32:10.730Z","v":0}

And if I change currency in config:

{"name":"tribeca:main","hostname":"scw-d786d3","pid":20491,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-18T03:33:40.388Z","v":0}
{"name":"tribeca:main","hostname":"scw-d786d3","pid":20491,"level":50,"err":{"message":"Unsupported currency CNY","name":"Error","stack":"Error: Unsupported currency CNY\n    at GetCurrencySymbol (/home/tribeca/app/service/gateways/okcoin.js:346:24)\n    at new OkCoinSymbolProvider (/home/tribeca/app/service/gateways/okcoin.js:351:60)\n    at OkCoin (/home/tribeca/app/service/gateways/okcoin.js:357:22)\n    at Object.getExch (/home/tribeca/app/service/main.js:178:50)\n    at Q.all.spread.err (/home/tribeca/app/service/main.js:264:31)\n    at /home/tribeca/node_modules/q/q.js:1229:26\n    at _fulfilled (/home/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/home/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/home/tribeca/node_modules/q/q.js:796:13)\n    at /home/tribeca/node_modules/q/q.js:556:49"},"msg":"Unhandled exception!","time":"2017-01-18T03:33:40.563Z","v":0}
/home/tribeca/app/service/main.js:67
    Q.timeout(exitingEvent(), 2000).then(completed => {
              ^

TypeError: exitingEvent is not a function
    at performExit (/home/tribeca/app/service/main.js:67:15)
    at process.on.err (/home/tribeca/app/service/main.js:80:5)
    at emitOne (events.js:96:13)
    at process.emit (events.js:188:7)
    at process._fatalException (bootstrap_node.js:296:26)

🙏 So I guess now its time to ask for adding support of okcoin.cn and CNY currency :)

ctubio commented 7 years ago

Just added CNY support, please if you agree let me know if you have any other issues with CNY, im not able to trade in that currency from my country :sob: (i believe that okcoin.cn support is achieved by setting the correct urls in the configs [so nothing change in the code], but i can't test it)

many many thanks for your bug report!

Bzzz666 commented 7 years ago

Hi. Thx to you for support and reaction! I am still experiencing problems. I have replaced USD mentions with CNY in okcoin.ts and API urls in the configuration file.

That's how they look now:

}


- okcoin.ts

/// /// /// ///

import ws = require('ws'); import Q = require("q"); import crypto = require("crypto"); import request = require("request"); import url = require("url"); import querystring = require("querystring"); import Config = require("../config"); import NullGateway = require("./nullgw"); import Models = require("../../common/models"); import Utils = require("../utils"); import util = require("util"); import Interfaces = require("../interfaces"); import moment = require("moment"); import _ = require("lodash"); var shortId = require("shortid");

interface OkCoinMessageIncomingMessage { channel : string; success : string; data : any; event? : string; }

interface OkCoinDepthMessage { asks : [number, number][]; bids : [number, number][]; timestamp : string; }

interface OrderAck { result: string; // "true" or "false" order_id: number; }

interface SignedMessage { api_key?: string; sign?: string; }

interface Order extends SignedMessage { symbol: string; type: string; price: string; amount: string; }

interface Cancel extends SignedMessage { order_id: string; symbol: string; }

interface OkCoinTradeRecord { averagePrice: string; completedTradeAmount: string; createdDate: string; id: string; orderId: string; sigTradeAmount: string; sigTradePrice: string; status: number; symbol: string; tradeAmount: string; tradePrice: string; tradeType: string; tradeUnitPrice: string; unTrade: string; }

interface SubscriptionRequest extends SignedMessage { }

class OkCoinWebsocket { send = (channel : string, parameters: any) => { var subsReq : any = {event: 'addChannel', channel: channel};

    if (parameters !== null)
        subsReq.parameters = parameters;

    this._ws.send(JSON.stringify(subsReq));
}

setHandler = <T>(channel : string, handler: (newMsg : Models.Timestamped<T>) => void) => {
    this._handlers[channel] = handler;
}

private onMessage = (raw : string) => {
    var t = Utils.date();
    try {
        var msg : OkCoinMessageIncomingMessage = JSON.parse(raw)[0];

        if (typeof msg.event !== "undefined" && msg.event == "ping") {
            this._ws.send(this._serializedHeartbeat);
            return;
        }

        if (typeof msg.success !== "undefined") {
            if (msg.success !== "true")
                this._log.warn("Unsuccessful message", msg);
            else
                this._log.info("Successfully connected to %s", msg.channel);
            return;
        }

        var handler = this._handlers[msg.channel];

        if (typeof handler === "undefined") {
            this._log.warn("Got message on unknown topic", msg);
            return;
        }

        handler(new Models.Timestamped(msg.data, t));
    }
    catch (e) {
        this._log.error(e, "Error parsing msg %o", raw);
        throw e;
    }
};

ConnectChanged = new Utils.Evt<Models.ConnectivityStatus>();
private _serializedHeartbeat = JSON.stringify({event: "pong"});
private _log = Utils.log("tribeca:gateway:OkCoinWebsocket");
private _handlers : { [channel : string] : (newMsg : Models.Timestamped<any>) => void} = {};
private _ws : ws;
constructor(config : Config.IConfigProvider) {
    this._ws = new ws(config.GetString("OkCoinWsUrl"));

    this._ws.on("open", () => this.ConnectChanged.trigger(Models.ConnectivityStatus.Connected));
    this._ws.on("message", this.onMessage);
    this._ws.on("close", () => this.ConnectChanged.trigger(Models.ConnectivityStatus.Disconnected));
}

}

class OkCoinMarketDataGateway implements Interfaces.IMarketDataGateway { ConnectChanged = new Utils.Evt();

MarketTrade = new Utils.Evt<Models.GatewayMarketTrade>();
private onTrade = (trades : Models.Timestamped<[string,string,string,string,string][]>) => {
    // [tid, price, amount, time, type]
    _.forEach(trades.data, trade => {
        var px = parseFloat(trade[1]);
        var amt = parseFloat(trade[2]);
        var side = trade[4] === "ask" ? Models.Side.Ask : Models.Side.Bid; // is this the make side?
        var mt = new Models.GatewayMarketTrade(px, amt, trades.time, trades.data.length > 0, side);
        this.MarketTrade.trigger(mt);
    });
};

MarketData = new Utils.Evt<Models.Market>();

private static GetLevel = (n: [number, number]) : Models.MarketSide =>
    new Models.MarketSide(n[0], n[1]);

private onDepth = (depth : Models.Timestamped<OkCoinDepthMessage>) => {
    var msg = depth.data;

    var bids = _(msg.bids).take(9).map(OkCoinMarketDataGateway.GetLevel).value();
    var asks = _(msg.asks).reverse().take(9).map(OkCoinMarketDataGateway.GetLevel).value()
    var mkt = new Models.Market(bids, asks, depth.time);

    this.MarketData.trigger(mkt);
};

private _log = Utils.log("tribeca:gateway:OkCoinMD");
constructor(socket : OkCoinWebsocket, symbolProvider: OkCoinSymbolProvider) {
    var depthChannel = "ok_" + symbolProvider.symbolWithoutUnderscore + "_depth";
    var tradesChannel = "ok_" + symbolProvider.symbolWithoutUnderscore + "_trades_v1";

    socket.setHandler(depthChannel, this.onDepth);
    socket.setHandler(tradesChannel, this.onTrade);

    socket.ConnectChanged.on(cs => {
        this.ConnectChanged.trigger(cs);

        if (cs == Models.ConnectivityStatus.Connected) {
            socket.send(depthChannel, {});
            socket.send(tradesChannel, {});
        }
    });
}

}

class OkCoinOrderEntryGateway implements Interfaces.IOrderEntryGateway { OrderUpdate = new Utils.Evt(); ConnectChanged = new Utils.Evt();

generateClientOrderId = () => shortId.generate();

supportsCancelAllOpenOrders = () : boolean => { return false; };
cancelAllOpenOrders = () : Q.Promise<number> => { return Q(0); };

public cancelsByClientOrderId = false;

private static GetOrderType(side: Models.Side, type: Models.OrderType) : string {
    if (side === Models.Side.Bid) {
        if (type === Models.OrderType.Limit) return "buy";
        if (type === Models.OrderType.Market) return "buy_market";
    }
    if (side === Models.Side.Ask) {
        if (type === Models.OrderType.Limit) return "sell";
        if (type === Models.OrderType.Market) return "sell_market";
    }
    throw new Error("unable to convert " + Models.Side[side] + " and " + Models.OrderType[type]);
}

// let's really hope there's no race conditions on their end -- we're assuming here that orders sent first
// will be acked first, so we can match up orders and their acks
private _ordersWaitingForAckQueue = [];

sendOrder = (order : Models.BrokeredOrder) : Models.OrderGatewayActionReport => {
    var o : Order = {
        symbol: this._symbolProvider.symbol,
        type: OkCoinOrderEntryGateway.GetOrderType(order.side, order.type),
        price: order.price.toString(),
        amount: order.quantity.toString()};

    this._ordersWaitingForAckQueue.push(order.orderId);

    this._socket.send<OrderAck>("ok_spotcny_trade", this._signer.signMessage(o));
    return new Models.OrderGatewayActionReport(Utils.date());
};

private onOrderAck = (ts: Models.Timestamped<OrderAck>) => {
    var orderId = this._ordersWaitingForAckQueue.shift();
    if (typeof orderId === "undefined") {
        this._log.error("got an order ack when there was no order queued!", util.format(ts.data));
        return;
    }

    var osr : Models.OrderStatusReport = { orderId: orderId, time: ts.time };

    if (ts.data.result === "true") {
        osr.exchangeId = ts.data.order_id.toString();
        osr.orderStatus = Models.OrderStatus.Working;
    }
    else {
        osr.orderStatus = Models.OrderStatus.Rejected;
    }

    this.OrderUpdate.trigger(osr);
};

cancelOrder = (cancel : Models.BrokeredCancel) : Models.OrderGatewayActionReport => {
    var c : Cancel = {order_id: cancel.exchangeId, symbol: this._symbolProvider.symbol };
    this._socket.send<OrderAck>("ok_spotcny_cancel_order", this._signer.signMessage(c));
    return new Models.OrderGatewayActionReport(Utils.date());
};

private onCancel = (ts: Models.Timestamped<OrderAck>) => {
    var osr : Models.OrderStatusReport = { exchangeId: ts.data.order_id.toString(), time: ts.time };

    if (ts.data.result === "true") {
        osr.orderStatus = Models.OrderStatus.Cancelled;
    }
    else {
        osr.orderStatus = Models.OrderStatus.Rejected;
        osr.cancelRejected = true;
    }

    this.OrderUpdate.trigger(osr);
};

replaceOrder = (replace : Models.BrokeredReplace) : Models.OrderGatewayActionReport => {
    this.cancelOrder(new Models.BrokeredCancel(replace.origOrderId, replace.orderId, replace.side, replace.exchangeId));
    return this.sendOrder(replace);
};

private static getStatus(status: number) : Models.OrderStatus {
    // status: -1: cancelled, 0: pending, 1: partially filled, 2: fully filled, 4: cancel request in process
    switch (status) {
        case -1: return Models.OrderStatus.Cancelled;
        case 0: return Models.OrderStatus.Working;
        case 1: return Models.OrderStatus.Working;
        case 2: return Models.OrderStatus.Complete;
        case 4: return Models.OrderStatus.Working;
        default: return Models.OrderStatus.Other;
    }
}

private onTrade = (tsMsg : Models.Timestamped<OkCoinTradeRecord>) => {
    var t = tsMsg.time;
    var msg : OkCoinTradeRecord = tsMsg.data;

    var avgPx = parseFloat(msg.averagePrice);
    var lastQty = parseFloat(msg.sigTradeAmount);
    var lastPx = parseFloat(msg.sigTradePrice);

    var status : Models.OrderStatusReport = {
        exchangeId: msg.orderId.toString(),
        orderStatus: OkCoinOrderEntryGateway.getStatus(msg.status),
        time: t,
        lastQuantity: lastQty > 0 ? lastQty : undefined,
        lastPrice: lastPx > 0 ? lastPx : undefined,
        averagePrice: avgPx > 0 ? avgPx : undefined,
        pendingCancel: msg.status === 4,
        partiallyFilled: msg.status === 1
    };

    this.OrderUpdate.trigger(status);
};

private _log = Utils.log("tribeca:gateway:OkCoinOE");
constructor(
        private _socket : OkCoinWebsocket,
        private _signer: OkCoinMessageSigner,
        private _symbolProvider: OkCoinSymbolProvider) {
    _socket.setHandler("ok_cny_realtrades", this.onTrade);
    _socket.setHandler("ok_spotcny_trade", this.onOrderAck);
    _socket.setHandler("ok_spotcny_cancel_order", this.onCancel);

    _socket.ConnectChanged.on(cs => {
        this.ConnectChanged.trigger(cs);

        if (cs === Models.ConnectivityStatus.Connected) {
            _socket.send("ok_cny_realtrades", _signer.signMessage({}));
        }
    });
}

}

class OkCoinMessageSigner { private _secretKey : string; private _api_key : string;

public signMessage = (m : SignedMessage) : SignedMessage => {
    var els : string[] = [];

    if (!m.hasOwnProperty("api_key"))
        m.api_key = this._api_key;

    var keys = [];
    for (var key in m) {
        if (m.hasOwnProperty(key))
            keys.push(key);
    }
    keys.sort();

    for (var i = 0; i < keys.length; i++) {
        const k = keys[i];
        if (m.hasOwnProperty(k))
            els.push(k + "=" + m[k]);
    }

    var sig = els.join("&") + "&secret_key=" + this._secretKey;
    m.sign = crypto.createHash('md5').update(sig).digest("hex").toString().toUpperCase();
    return m;
};

constructor(config : Config.IConfigProvider) {
    this._api_key = config.GetString("OkCoinApiKey");
    this._secretKey = config.GetString("OkCoinSecretKey");
}

}

class OkCoinHttp { post = (actionUrl: string, msg : SignedMessage) : Q.Promise<Models.Timestamped> => { var d = Q.defer<Models.Timestamped>();

    request({
        url: url.resolve(this._baseUrl, actionUrl),
        body: querystring.stringify(this._signer.signMessage(msg)),
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        method: "POST"
    }, (err, resp, body) => {
        if (err) d.reject(err);
        else {
            try {
                var t = Utils.date();
                var data = JSON.parse(body);
                d.resolve(new Models.Timestamped(data, t));
            }
            catch (e) {
                this._log.error(err, "url: %s, err: %o, body: %o", actionUrl, err, body);
                d.reject(e);
            }
        }
    });

    return d.promise;
};

private _log = Utils.log("tribeca:gateway:OkCoinHTTP");
private _baseUrl : string;
constructor(config : Config.IConfigProvider, private _signer: OkCoinMessageSigner) {
    this._baseUrl = config.GetString("OkCoinHttpUrl")
}

}

class OkCoinPositionGateway implements Interfaces.IPositionGateway { PositionUpdate = new Utils.Evt();

private static convertCurrency(name : string) : Models.Currency {
    switch (name.toLowerCase()) {
        case "cny": return Models.Currency.CNY;
        case "ltc": return Models.Currency.LTC;
        case "btc": return Models.Currency.BTC;
        default: throw new Error("Unsupported currency " + name);
    }
}

private trigger = () => {
    this._http.post("userinfo.do", {}).then(msg => {
        var free = (<any>msg.data).info.funds.free;
        var freezed = (<any>msg.data).info.funds.freezed;

        for (var currencyName in free) {
            if (!free.hasOwnProperty(currencyName)) continue;
            var amount = parseFloat(free[currencyName]);
            var held = parseFloat(freezed[currencyName]);

            var pos = new Models.CurrencyPosition(amount, held, OkCoinPositionGateway.convertCurrency(currencyName));
            this.PositionUpdate.trigger(pos);
        }
    }).done();
};

private _log = Utils.log("tribeca:gateway:OkCoinPG");
constructor(private _http : OkCoinHttp) {
    setInterval(this.trigger, 15000);
    setTimeout(this.trigger, 10);
}

}

class OkCoinBaseGateway implements Interfaces.IExchangeDetailsGateway { public get hasSelfTradePrevention() { return false; }

name() : string {
    return "OkCoin";
}

makeFee() : number {
    return 0.001;
}

takeFee() : number {
    return 0.002;
}

exchange() : Models.Exchange {
    return Models.Exchange.OkCoin;
}

private static AllPairs = [
    new Models.CurrencyPair(Models.Currency.BTC, Models.Currency.CNY),
    //new Models.CurrencyPair(Models.Currency.LTC, Models.Currency.CNY),
];
public get supportedCurrencyPairs() {
    return OkCoinBaseGateway.AllPairs;
}

}

function GetCurrencyEnum(c: string) : Models.Currency { switch (c.toLowerCase()) { case "cny": return Models.Currency.CNY; case "ltc": return Models.Currency.LTC; case "btc": return Models.Currency.BTC; default: throw new Error("Unsupported currency " + c); } }

function GetCurrencySymbol(c: Models.Currency) : string { switch (c) { case Models.Currency.CNY: return "cny"; case Models.Currency.LTC: return "ltc"; case Models.Currency.BTC: return "btc"; default: throw new Error("Unsupported currency " + Models.Currency[c]); } }

class OkCoinSymbolProvider { public symbol : string; public symbolWithoutUnderscore: string;

constructor(pair: Models.CurrencyPair) {
    this.symbol = GetCurrencySymbol(pair.base) + "_" + GetCurrencySymbol(pair.quote);
    this.symbolWithoutUnderscore = GetCurrencySymbol(pair.base) + GetCurrencySymbol(pair.quote);
}

}

export class OkCoin extends Interfaces.CombinedGateway { constructor(config : Config.IConfigProvider, pair: Models.CurrencyPair) { var symbol = new OkCoinSymbolProvider(pair); var signer = new OkCoinMessageSigner(config); var http = new OkCoinHttp(config, signer); var socket = new OkCoinWebsocket(config);

    var orderGateway = config.GetString("OkCoinOrderDestination") == "OkCoin"
        ? <Interfaces.IOrderEntryGateway>new OkCoinOrderEntryGateway(socket, signer, symbol)
        : new NullGateway.NullOrderGateway();

    super(
        new OkCoinMarketDataGateway(socket, symbol),
        orderGateway,
        new OkCoinPositionGateway(http),
        new OkCoinBaseGateway());
    }

}


I tried reset to older commit version (few days earlier, before fix-commit with new error msg).
In the older versions, the log shows this(I check to confirm some log lines):

warn: --minUptime not set. Defaulting to: 1000ms warn: --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-18T21:36:54.374Z","v":0} {"name":"tribeca:active","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Starting saved quoting state: true","time":"2017-01-18T21:36:54.700Z","v":0} {"name":"ewma","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-18T21:36:54.727Z","v":0} {"name":"tribeca:active","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-18T21:36:56.077Z","v":0} {"name":"tribeca:gateway:OkCoinWebsocket","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Successfully connected to ok_cny_realtrades","time":"2017-01-18T21:36:56.415Z","v":0} {"name":"tribeca:gateway:OkCoinWebsocket","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Successfully connected to ok_btccny_depth","time":"2017-01-18T21:36:56.419Z","v":0} {"name":"tribeca:gateway:OkCoinWebsocket","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Successfully connected to ok_btccny_trades_v1","time":"2017-01-18T21:36:56.434Z","v":0} {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Event looped blocked for 315.96ms","time":"2017-01-18T21:36:56.818Z","v":0} {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:283:41)\n at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n at /tribeca/node_modules/q/q.js:604:44\n at runSingle (/tribeca/node_modules/q/q.js:137:13)\n at flush (/tribeca/node_modules/q/q.js:125:13)\n at _combinedTickCallback (internal/process/next_tick.js:67:7)\n at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-18T21:36:57.316Z","v":0} {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"persisting active to true","time":"2017-01-18T21:36:57.318Z","v":0} {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-18T21:36:57.331Z","v":0} {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-18T21:36:57.332Z","v":0} {"name":"tribeca:main","hostname":"f2d5e060bf8c","pid":16,"level":30,"msg":"Exiting with code 0","time":"2017-01-18T21:36:57.333Z","v":0} error: Forever detected script exited with code: 0 error: Script restart attempt #1


And then again the same error 
> "Cannot read property 'funds' of undefined"

So has connected to api.... ok.

And log from the latest version:

warn: --minUptime not set. Defaulting to: 1000ms warn: --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms {"name":"tribeca:main","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-18T22:23:25.422Z","v":0} {"name":"tribeca:active","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"Starting saved quoting state: true","time":"2017-01-18T22:23:25.759Z","v":0} {"name":"ewma","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-18T22:23:25.789Z","v":0} {"name":"tribeca:gateway:OkCoinPG","hostname":"f6b8fd7701e4","pid":16,"level":50,"msg":"Please change the API Key or contact support team of OkCoin, your API Key does not work because was not possible to retrieve your real wallet position; the application will probably crash now.","time":"2017-01-18T22:23:26.704Z","v":0} {"name":"tribeca:main","hostname":"f6b8fd7701e4","pid":16,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:285:41)\n at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n at /tribeca/node_modules/q/q.js:604:44\n at runSingle (/tribeca/node_modules/q/q.js:137:13)\n at flush (/tribeca/node_modules/q/q.js:125:13)\n at _combinedTickCallback (internal/process/next_tick.js:67:7)\n at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-18T22:23:26.715Z","v":0} {"name":"tribeca:main","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"persisting active to true","time":"2017-01-18T22:23:26.717Z","v":0} {"name":"tribeca:main","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-18T22:23:26.740Z","v":0} {"name":"tribeca:main","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-18T22:23:26.742Z","v":0} {"name":"tribeca:main","hostname":"f6b8fd7701e4","pid":16,"level":30,"msg":"Exiting with code 0","time":"2017-01-18T22:23:26.743Z","v":0} error: Forever detected script exited with code: 0 error: Script restart attempt #1



same :( as was.

Sorry for long code pastes, was no possible use git normal at this time :) 

If it will be helpfull I can create and share new api credentials for dev\test purpose. 
ctubio commented 7 years ago

Hello Bzzz666, can you please send me the test keys for CNY currency? i cant create one from my country (and will be faster yea if i can test localy, many thanks in advance'¡!).

I think i understand your point, okcoin.ts was not only not supporting CNY currency but also is still using api methods for USD, so that must be fixed too to fully support CNY trading. understood! will try to fix it sOOn.

USD docs https://www.okcoin.com/about/ws_api.do CNY docs https://www.okcoin.cn/ws_api.html ERR docs https://www.okcoin.com/rest_request.html

Bzzz666 commented 7 years ago

done!

ctubio commented 7 years ago

now for me is working nice. (please note with test api keys doesn't work, tribeca seems to not like the sandbox of okcoin yet)

Can you please let me know if is resolved for you the issue with production CNY key? Thanks¡'!

Bzzz666 commented 7 years ago
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
{"name":"tribeca:main","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Listening to admins on *: 3000","time":"2017-01-21T19:53:42.243Z","v":0}
{"name":"tribeca:active","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Starting saved quoting state:  false","time":"2017-01-21T19:53:42.491Z","v":0}
{"name":"ewma","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-21T19:53:42.515Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Successfully connected to ok_cny_realtrades","time":"2017-01-21T19:53:45.324Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Successfully connected to ok_btccny_depth","time":"2017-01-21T19:53:45.326Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Successfully connected to ok_btccny_trades_v1","time":"2017-01-21T19:53:45.350Z","v":0}
{"name":"tribeca:main","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Event looped blocked for 255.28ms","time":"2017-01-21T19:53:45.639Z","v":0}
{"name":"tribeca:gateway:OkCoinPG","hostname":"9aede8b7fef4","pid":15,"level":50,"msg":"Please change the API Key or contact support team of OkCoin, your API Key does not work because was not possible to retrieve your real wallet position; the application will probably crash now.","time":"2017-01-21T19:53:47.060Z","v":0}
{"name":"tribeca:main","hostname":"9aede8b7fef4","pid":15,"level":50,"err":{"message":"Cannot read property 'funds' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'funds' of undefined\n    at _http.post.then.msg (/tribeca/app/service/gateways/okcoin.js:290:41)\n    at _fulfilled (/tribeca/node_modules/q/q.js:834:54)\n    at self.promiseDispatch.done (/tribeca/node_modules/q/q.js:863:30)\n    at Promise.promise.promiseDispatch (/tribeca/node_modules/q/q.js:796:13)\n    at /tribeca/node_modules/q/q.js:604:44\n    at runSingle (/tribeca/node_modules/q/q.js:137:13)\n    at flush (/tribeca/node_modules/q/q.js:125:13)\n    at _combinedTickCallback (internal/process/next_tick.js:67:7)\n    at process._tickCallback (internal/process/next_tick.js:98:9)"},"msg":"Unhandled exception!","time":"2017-01-21T19:53:47.068Z","v":0}
{"name":"tribeca:main","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Cancelled all 0 open orders","time":"2017-01-21T19:53:47.074Z","v":0}
{"name":"tribeca:main","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"All exiting event handlers have fired, exiting application.","time":"2017-01-21T19:53:47.075Z","v":0}
{"name":"tribeca:main","hostname":"9aede8b7fef4","pid":15,"level":30,"msg":"Exiting with code 0","time":"2017-01-21T19:53:47.076Z","v":0}
error: Forever detected script exited with code: 0
error: Script restart attempt #1
ctubio commented 7 years ago

Please can you confirm if the test api key have trades enabled? im getting:

{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":31269,"level":40,"msg":"Unsuccessful message { channel: 'ok_cny_realtrades',\n  errorcode: '10002',\n  success: 'false' }","time":"2017-01-21T20:20:24.439Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":31269,"level":30,"msg":"Successfully connected to ok_btccny_depth","time":"2017-01-21T20:20:24.440Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":31269,"level":30,"msg":"Successfully connected to ok_btccny_trades_v1","time":"2017-01-21T20:20:24.451Z","v":0}

If i use my api keys, seems to work (but i have no funds in .cn because i cant be verified):

$ nodejs tribeca.js
{"name":"tribeca:main","hostname":"mailbox","pid":31382,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-21T20:43:38.671Z","v":0}
{"name":"tribeca:main","hostname":"mailbox","pid":31382,"level":30,"msg":"Listening to admins on *: 9333","time":"2017-01-21T20:43:38.768Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":31382,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-21T20:43:39.021Z","v":0}
{"name":"ewma","hostname":"mailbox","pid":31382,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-21T20:43:39.031Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":31382,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-21T20:43:40.130Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":31382,"level":30,"msg":"Successfully connected to ok_cny_realtrades","time":"2017-01-21T20:43:40.407Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":31382,"level":30,"msg":"Successfully connected to ok_btccny_depth","time":"2017-01-21T20:43:40.408Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":31382,"level":30,"msg":"Successfully connected to ok_btccny_trades_v1","time":"2017-01-21T20:43:40.422Z","v":0}
{"name":"positionmanager","hostname":"mailbox","pid":31382,"level":30,"msg":"recalculated target base position: 0","time":"2017-01-21T20:43:55.600Z","v":0}

i used the following urls:

    "OkCoinWsUrl": "wss://real.okcoin.cn:10440/websocket/okcoinapi",
    "OkCoinHttpUrl": "https://www.okcoin.cn/api/v1/",
Bzzz666 commented 7 years ago

just activated trading options on api keys.

I got these errors on trade activated keys.

ctubio commented 7 years ago

For me your keys (from my inbox) are working OK, this is my log:

$ nodejs tribeca.js
{"name":"tribeca:main","hostname":"mailbox","pid":32174,"level":30,"msg":"Requiring authentication to web client","time":"2017-01-23T13:04:32.673Z","v":0}
{"name":"tribeca:main","hostname":"mailbox","pid":32174,"level":30,"msg":"Listening to admins on *: 9333","time":"2017-01-23T13:04:32.761Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":32174,"level":30,"msg":"Starting saved quoting state:  true","time":"2017-01-23T13:04:32.855Z","v":0}
{"name":"ewma","hostname":"mailbox","pid":32174,"level":30,"msg":"Unable to compute EMWA value","time":"2017-01-23T13:04:32.861Z","v":0}
{"name":"tribeca:active","hostname":"mailbox","pid":32174,"level":30,"msg":"Changed quoting mode to true","time":"2017-01-23T13:04:34.938Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":32174,"level":30,"msg":"Successfully connected to ok_cny_realtrades","time":"2017-01-23T13:04:35.186Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":32174,"level":30,"msg":"Successfully connected to ok_btccny_depth","time":"2017-01-23T13:04:35.188Z","v":0}
{"name":"tribeca:gateway:OkCoinWebsocket","hostname":"mailbox","pid":32174,"level":30,"msg":"Successfully connected to ok_btccny_trades_v1","time":"2017-01-23T13:04:35.200Z","v":0}
{"name":"positionmanager","hostname":"mailbox","pid":32174,"level":30,"msg":"recalculated target base position: 0","time":"2017-01-23T13:04:48.145Z","v":0}

Make sure you are using the urls:

   "OkCoinWsUrl": "wss://real.okcoin.cn:10440/websocket/okcoinapi",
    "OkCoinHttpUrl": "https://www.okcoin.cn/api/v1/",

I can't imagine what is wrong for you because for me is working, im able to get the "funds" values from okcoin.cn key: cny

Maybe you can ask to OkCoin support team for any help? oor.. please paste again your log after running the last tribeca version? (just to make sure that i really can't do nothing else before go to OkCoin support team)

ctubio commented 7 years ago

Closing issue meanwhile no more comments are added. Sadly im not able to reproduce the error yet, but i would love to try again if you still need help and provide new info that allows me to reproduce the error. I still keep an eye to this issue if ever updated!

Camille92 commented 7 years ago

Hey maybe it's linked so I comment here.

I'm testing Okcoin (USD) and indeed the orders don't stay up.

As well tribeca credits me with a negative balance and more than what I have in position.

I was thinking maybe it can be due to the request limit ?

I've been reading here : https://github.com/you21979/node-okcoin that the limit is 3000 request every 5mn. capture d ecran 2017-01-28 a 16 10 46

ctubio commented 7 years ago

Hello Camille, this is about connection problem to CNY, but related to your issue, i dont think is because the request limit, otherwise you will get an error 10001 Request frequency too high (see https://www.okcoin.com/rest_request.html) and no information will be displayed.

I belive this negative values are because the okcoin gateway is not cleaning up closed or rejected or canceled orders correctly, and it calculates more amount held of what really exists; will investigate! - thanks for the report.

This may happen since tribeca calculates its own position based on the placed orders instead of request the positiont to the gateway (to save bandwidth and add realtime instead of 10sec interval update)

Camille92 commented 7 years ago

Thank you for the quick feedback.

As a more general question, is OkCoin (usd) working for you or it is still under investigation ?

Cheers!

ctubio commented 7 years ago

For me is working fine, but i only tested for 10minutes and may be still not perfect the calculation in okcoin gateway, already applied fixes: be212e0 Fixed zombie OkCoin trades. 8c0beb6 Fixed trades lifetime in OkCoin gateway.

lets see if next fix is the definitive :P Salut'¡

Camille92 commented 7 years ago

After pausing the bot a little bit (40 minutes):

_There is no negative value and it shows the good numbers.

_ The number of trade greatly augmented from 1 every 15 seg to one or two every seg.

Camille92 commented 7 years ago

Thank you,

Yes hopefully!

Camille92 commented 7 years ago

Ps: I sent you an email at ctubio@users.noreply.github.com did you receive it ? 😉

ctubio commented 7 years ago

lol no (but i yesreply private msgs at -see profile- even if you get a bouncing error [still trying to fix the ipv6 while relaying mails to my secondary inboxes..])