├── .babelrc ├── .editorconfig ├── .eslintrc ├── .flowconfig ├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── bin ├── blinktrade-dev ├── blinktrade.js ├── cli.js ├── dispatch.js ├── interactive.js ├── logger.js ├── program.js └── prompts.js ├── examples ├── README.md ├── authWebSocket.js ├── balance.js ├── deposits.js ├── eventEmitters.js ├── executionReport.js ├── index.html ├── myOrders.js ├── orderBookWebSocket.js ├── package.json ├── publicRest.js ├── requestDepositList.js ├── requestWithdrawList.js ├── sendAndCancelOrdersRest.js ├── sendAndCancelOrdersWebSocket.js ├── tickerWebSocket.js ├── tradeHistory.js ├── tsconfig.json ├── typescript.ts └── withdraw.js ├── index.d.ts ├── package.json ├── rollup.config.js ├── src ├── constants │ ├── actionTypes.js │ ├── brokers.js │ ├── common.js │ ├── markets.js │ ├── messages.js │ ├── requestTypes.js │ └── utils.js ├── index.js ├── listener.js ├── rest.js ├── trade.js ├── transports │ ├── __mocks__ │ │ ├── messages.js │ │ └── websocket.js │ ├── rest.js │ ├── transport.js │ └── websocket.js ├── types.js ├── util │ ├── __mocks__ │ │ ├── fingerPrint.js │ │ ├── macaddress.js │ │ └── stun.js │ ├── fingerPrint.js │ ├── hash32.js │ ├── macaddress.js │ ├── stun.js │ └── utils.js └── ws.js ├── test ├── browser │ └── browser.spec.js └── node │ ├── listener.spec.js │ ├── node.spec.js │ ├── rest.js │ └── websocket.spec.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "test": { 4 | "presets": ["@babel/preset-env", "@babel/preset-flow"] 5 | } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | charset = utf-8 6 | trim_trailing_whitespace = true 7 | insert_final_newline = true 8 | indent_style = space 9 | indent_size = 2 10 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["airbnb-base", "plugin:flowtype/recommended"], 3 | "parser": "babel-eslint", 4 | "rules": { 5 | "flowtype/space-after-type-colon": 0, 6 | "flowtype/semi": [2, "always"], 7 | "flowtype/object-type-delimiter": [2, "comma"], 8 | "indent": ["error", 2, { "ignoredNodes": ["ConditionalExpression"], "SwitchCase": 1 }], 9 | "import/prefer-default-export": 0, 10 | "prefer-template": 0, 11 | "key-spacing": 0, 12 | "max-len": 0, 13 | "no-console": 0, 14 | "radix": 0, 15 | "global-require": 0, 16 | "arrow-body-style": 0, 17 | "arrow-parens": 0, 18 | "consistent-return": 0, 19 | "quote-props": 0, 20 | "no-bitwise": 0, 21 | "no-nested-ternary": 0, 22 | "no-multi-spaces": 0, 23 | "no-unused-expressions": 0, 24 | "no-case-declarations": 0, 25 | "newline-per-chained-call": 0, 26 | "class-methods-use-this": 0, 27 | "object-curly-spacing": ["error", "always", { "objectsInObjects": false }], 28 | "import/no-extraneous-dependencies": [2, { devDependencies: true }], 29 | "no-unused-vars": [2, {"varsIgnorePattern": "Columns|VerificationData" }], 30 | "new-cap": [2, { "newIsCapExceptions": [ "hmac" ] }], 31 | "object-curly-newline": 0 32 | }, 33 | "globals": { 34 | "window": true, 35 | "document": true, 36 | "describe": true, 37 | "expect": true, 38 | "test": true, 39 | "jest": true 40 | }, 41 | "plugins": ["flowtype"] 42 | } 43 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ./dist/* 3 | ./lib/* 4 | .*/examples/node_modules/* 5 | .*/node_modules/editions/source/index.js 6 | .*/src/.*\.flow 7 | 8 | [include] 9 | 10 | [libs] 11 | flow-typed/ 12 | 13 | [options] 14 | suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/node 2 | 3 | ### Node ### 4 | # Logs 5 | logs 6 | *.log 7 | npm-debug.log* 8 | 9 | # Runtime data 10 | pids 11 | *.pid 12 | *.seed 13 | *.pid.lock 14 | 15 | # Directory for instrumented libs generated by jscoverage/JSCover 16 | lib-cov 17 | 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | 21 | # nyc test coverage 22 | .nyc_output 23 | 24 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 25 | .grunt 26 | 27 | # node-waf configuration 28 | .lock-wscript 29 | 30 | # Compiled binary addons (http://nodejs.org/api/addons.html) 31 | build/Release 32 | 33 | # Bundle examples 34 | examples/browser/bundle 35 | 36 | # Dependency directories 37 | node_modules 38 | jspm_packages 39 | 40 | # prepublish compiled 41 | lib 42 | dist 43 | es 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Optional REPL history 52 | .node_repl_history 53 | 54 | flow-typed/ 55 | *.flow 56 | 57 | # cli 58 | bin/blinktrade 59 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | examples 2 | flow-typed 3 | test 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "8.9.4" 4 | before_install: 5 | - npm install 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /bin/blinktrade-dev: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | require('@babel/register')({ 4 | presets: [ 5 | '@babel/preset-env', 6 | '@babel/preset-flow', 7 | ], 8 | }); 9 | require('regenerator-runtime/runtime'); 10 | require('./program').default(); 11 | -------------------------------------------------------------------------------- /bin/blinktrade.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import 'regenerator-runtime/runtime'; 3 | import cli from './program'; 4 | 5 | cli(); 6 | -------------------------------------------------------------------------------- /bin/cli.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import invariant from 'invariant'; 3 | 4 | import { BlinkTradeWS, BlinkTradeRest } from '../lib/blinktrade'; 5 | 6 | import type { OrderSide, OrderType, OrderFilter } from '../src/types'; 7 | import type { Commands } from './program'; 8 | 9 | type Undefined = typeof undefined; 10 | 11 | type Transports = BlinkTradeRest | BlinkTradeWS; 12 | 13 | const parseNumber = (value: ?string): number | Undefined => (value ? parseInt(value) : undefined); 14 | 15 | const STATUS = { 16 | all: [], 17 | unconfirmed: ['0'], 18 | pending: ['1'], 19 | inprogress: ['2'], 20 | completed: ['4'], 21 | cancelled: ['8'], 22 | }; 23 | 24 | export class BaseCLI { 25 | $key: Commands; 26 | $value: void; 27 | 28 | +blinktrade: Transports; 29 | 30 | constructor(blinktrade: Transports) { 31 | this.blinktrade = blinktrade; 32 | } 33 | 34 | async balance() { 35 | return this.blinktrade.balance(); 36 | } 37 | 38 | async requestDeposit(options: { 39 | value?: string, 40 | method?: string, 41 | currency?: string, 42 | }) { 43 | if (options.currency !== 'BTC') { 44 | invariant(options.value, 'Error: --value is required'); 45 | invariant(options.method, 'Error: --data option is required'); 46 | } 47 | return this.blinktrade.requestDeposit({ 48 | value: options.value ? parseFloat(options.value) * 1e8 : undefined, 49 | depositMethodId: parseNumber(options.method), 50 | currency: options.currency, 51 | }); 52 | } 53 | 54 | async requestDepositList(options: { 55 | status?: string, 56 | page?: string, 57 | pageSize?: string, 58 | }) { 59 | return this.blinktrade.requestDepositList({ 60 | status: options.status ? STATUS[options.status] : [], 61 | page: parseNumber(options.page), 62 | pageSize: parseNumber(options.pageSize), 63 | }); 64 | } 65 | 66 | async requestWithdraw(options: { 67 | data: string, 68 | amount: string, 69 | method?: string, 70 | currency?: string, 71 | }) { 72 | invariant(options.amount, 'Error: --amount is required'); 73 | invariant(options.data, 'Error: --data option is required'); 74 | return this.blinktrade.requestWithdraw({ 75 | amount: parseFloat(options.amount) * 1e8, 76 | data: JSON.parse(options.data), 77 | method: options.method, 78 | currency: options.currency, 79 | }); 80 | } 81 | 82 | async requestWithdrawList(options: { 83 | status?: string, 84 | page?: string, 85 | pageSize?: string, 86 | }) { 87 | return this.blinktrade.requestWithdrawList({ 88 | status: options.status ? STATUS[options.status] : [], 89 | page: parseNumber(options.page), 90 | pageSize: parseNumber(options.pageSize), 91 | }); 92 | } 93 | 94 | async requestLedger(options: { 95 | page?: string, 96 | pageSize?: string, 97 | }) { 98 | return this.blinktrade.requestLedger({ 99 | page: parseNumber(options.page), 100 | pageSize: parseNumber(options.pageSize), 101 | }); 102 | } 103 | 104 | async requestBrokerList() { 105 | return this.blinktrade.requestBrokerList(); 106 | } 107 | 108 | async myOrders(options: { 109 | filter?: OrderFilter, 110 | page?: string, 111 | pageSize?: string, 112 | }) { 113 | return this.blinktrade.myOrders({ 114 | filter: options.filter, 115 | page: parseNumber(options.page), 116 | pageSize: parseNumber(options.pageSize), 117 | }); 118 | } 119 | 120 | async sendOrder(options: { 121 | side: OrderSide, 122 | type: OrderType, 123 | price?: string, 124 | amount?: string, 125 | symbol?: string, 126 | clientId?: string, 127 | postOnly?: boolean, 128 | stopPrice?: string, 129 | }) { 130 | invariant(options.price 131 | || options.type === 'MARKET' 132 | || options.type === 'STOP', 'Error: --price is required'); 133 | invariant(options.amount, 'Error: --amount is required'); 134 | invariant(options.symbol, 'Error: --symbol is required'); 135 | return this.blinktrade.sendOrder({ 136 | type: options.type, 137 | side: options.side, 138 | symbol: options.symbol, 139 | clientId: options.clientId, 140 | postOnly: options.postOnly, 141 | price: parseFloat(options.price) * 1e8, 142 | amount: parseFloat(options.amount) * 1e8, 143 | stopPrice: options.stopPrice ? parseInt(options.stopPrice) * 1e8 : undefined, 144 | }); 145 | } 146 | 147 | async cancelOrder(options: { 148 | orderId: string, 149 | clientId?: string, 150 | }) { 151 | invariant(options.orderId, 'Error: --orderId is required'); 152 | return this.blinktrade.cancelOrder({ 153 | orderId: parseInt(options.orderId), 154 | clientId: options.clientId, 155 | }); 156 | } 157 | } 158 | 159 | export class RestCLI extends BaseCLI { 160 | blinktrade: BlinkTradeRest; 161 | 162 | async ticker() { 163 | return this.blinktrade.ticker(); 164 | } 165 | 166 | async orderbook() { 167 | return this.blinktrade.orderbook(); 168 | } 169 | 170 | async trades(options: { 171 | limit?: string, 172 | since?: string, 173 | }) { 174 | return this.blinktrade.trades({ 175 | limit: parseNumber(options.limit), 176 | since: parseNumber(options.since), 177 | }); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /bin/dispatch.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import { RestCLI } from './cli'; 3 | import { InteractiveCLI } from './interactive'; 4 | import { logger } from './logger'; 5 | import { getEnvironment } from './program'; 6 | import { BlinkTradeWS, BlinkTradeRest } from '../lib/blinktrade'; 7 | 8 | import type { Options } from './program'; 9 | 10 | async function runner(interactive: InteractiveCLI) { 11 | const { action } = await interactive.promptMenu(); 12 | const method = interactive[action]; 13 | method && logger(await method.call(interactive)); 14 | runner(interactive); 15 | } 16 | 17 | export async function dispatchInteractive(options: Options) { 18 | try { 19 | const blinktrade = new BlinkTradeWS(getEnvironment(options)); 20 | const interactive = new InteractiveCLI(blinktrade); 21 | 22 | setInterval(() => interactive.heartbeat(), 10000); 23 | 24 | await blinktrade.connect(); 25 | await interactive.login(options); 26 | 27 | runner(interactive); 28 | 29 | blinktrade.on('ERROR', (error) => { 30 | console.log(error); 31 | runner(interactive); 32 | }); 33 | } catch (error) { 34 | console.log('Error', error); 35 | } 36 | } 37 | 38 | export async function dispatch(options: Options) { 39 | try { 40 | const blinktrade = new BlinkTradeRest({ 41 | ...getEnvironment(options), 42 | key: options.parent.key, 43 | secret: options.parent.secret, 44 | currency: options.currency, 45 | }); 46 | const cli = new RestCLI(blinktrade); 47 | const action = cli[options._name]; 48 | action && logger(await action.call(cli, options)); 49 | } catch (error) { 50 | console.log(error); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /bin/interactive.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import inquirer from 'inquirer'; 3 | import invariant from 'invariant'; 4 | 5 | import { BlinkTradeWS } from '../lib/blinktrade'; 6 | import { BaseCLI } from './cli'; 7 | import { getAuthentication } from './program'; 8 | import { 9 | promptMenu, 10 | promptLogin, 11 | promptStatus, 12 | promptMethod, 13 | promptCurrency, 14 | promptDepositRequest, 15 | promptWithdrawRequest, 16 | promptOrderHistory, 17 | promptOrderType, 18 | promptSendOrder, 19 | promptCancelOrder, 20 | } from './prompts'; 21 | 22 | import type { Options } from './program'; 23 | 24 | export class InteractiveCLI extends BaseCLI { 25 | blinktrade: BlinkTradeWS; 26 | 27 | async promptMenu() { 28 | return inquirer.prompt(promptMenu(!!this.blinktrade.session)); 29 | } 30 | 31 | async heartbeat() { 32 | return this.blinktrade.heartbeat(); 33 | } 34 | 35 | async login(options: Options) { 36 | console.log('Login'); 37 | const params = await getAuthentication(options, promptLogin); 38 | invariant( 39 | params.username && params.password, 40 | 'BLINKTRADE_API_KEY or BLINKTRADE_API_PASSWORD was not provided', 41 | ); 42 | await this.blinktrade.login({ ...params }); 43 | console.log('Logged Successfully'); 44 | // Don't print login message 45 | return false; 46 | } 47 | 48 | async requestDeposit() { 49 | const { currency } = await inquirer.prompt(promptCurrency); 50 | const data = currency !== 'BTC' 51 | ? (await inquirer.prompt(promptDepositRequest)) 52 | : {}; 53 | 54 | return super.requestDeposit({ ...data, value: data.amount, currency }); 55 | } 56 | 57 | async requestDepositList() { 58 | const { status } = await inquirer.prompt(promptStatus); 59 | return super.requestDepositList({ status: status.toLowerCase() }); 60 | } 61 | 62 | async requestWithdraw() { 63 | const { currency } = await inquirer.prompt(promptCurrency); 64 | const { method } = await inquirer.prompt(promptMethod); 65 | const data = await inquirer.prompt(promptWithdrawRequest); 66 | return super.requestWithdraw({ ...data, method, currency }); 67 | } 68 | 69 | async requestWithdrawList() { 70 | const { status } = await inquirer.prompt(promptStatus); 71 | return super.requestWithdrawList({ status: status.toLowerCase() }); 72 | } 73 | 74 | async myOrders() { 75 | const { filter } = await inquirer.prompt(promptOrderHistory); 76 | return super.myOrders({ filter }); 77 | } 78 | 79 | async sendOrder() { 80 | const { type } = await inquirer.prompt(promptOrderType); 81 | const data = await inquirer.prompt(promptSendOrder(type)); 82 | return super.sendOrder({ ...data, type }); 83 | } 84 | 85 | async cancelOrder() { 86 | const data = await inquirer.prompt(promptCancelOrder); 87 | return super.cancelOrder(data); 88 | } 89 | 90 | async logout() { 91 | console.log('Logging out...'); 92 | await this.blinktrade.logout(); 93 | process.exit(0); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /bin/logger.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | export function logger(data: Object) { 3 | if (data) { 4 | const { Columns, ...rest } = data; 5 | // TODO: Better logger printer 6 | console.log(''); 7 | console.log(rest); 8 | console.log(''); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /bin/program.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import dotenv from 'dotenv'; 5 | import program from 'commander'; 6 | import inquirer from 'inquirer'; 7 | import invariant from 'invariant'; 8 | 9 | import { version } from '../package.json'; 10 | import { promptLogin, promptRest } from './prompts'; 11 | import { 12 | dispatch, 13 | dispatchInteractive, 14 | } from './dispatch'; 15 | 16 | import type { BlinkTradeCurrencies } from '../src/types'; 17 | 18 | export type Commands = 19 | | 'ticker' 20 | | 'orderbook' 21 | | 'trades' 22 | | 'heartbeat' 23 | | 'login' 24 | | 'logout' 25 | | 'balance' 26 | | 'requestDeposit' 27 | | 'requestDepositList' 28 | | 'requestWithdraw' 29 | | 'requestWithdrawList' 30 | | 'requestLedger' 31 | | 'myOrders' 32 | | 'sendOrder' 33 | | 'cancelOrder'; 34 | 35 | type AuthPrompts = 36 | | typeof promptRest 37 | | typeof promptLogin; 38 | 39 | export type Options = { 40 | _name: Commands, 41 | currency?: BlinkTradeCurrencies, 42 | parent: { 43 | key?: string, 44 | secret?: string, 45 | prod?: boolean, 46 | credentials?: string, 47 | testnet?: boolean, 48 | brokerId?: number, 49 | }, 50 | }; 51 | 52 | function auth(callback) { 53 | return async (options: Options) => { 54 | const data = await getAuthentication(options, promptRest); 55 | invariant(data.key && data.secret, 'Key or secret was not provided'); 56 | return callback({ ...options, parent: { ...options.parent, ...data }}); 57 | }; 58 | } 59 | 60 | type AuthParsed = { 61 | key: string, 62 | secret: string, 63 | username: string, 64 | password: string, 65 | }; 66 | 67 | export function getAuthentication(options: Options, prompt: AuthPrompts): AuthParsed { 68 | const envPath = path.resolve(process.cwd(), options.parent.credentials || ''); 69 | 70 | if (fs.existsSync(envPath)) { 71 | dotenv.config({ path: envPath }); 72 | } 73 | 74 | const key = process.env.BLINKTRADE_API_KEY || ''; 75 | const secret = process.env.BLINKTRADE_API_SECRET || ''; 76 | const password = process.env.BLINKTRADE_API_PASSWORD || ''; 77 | 78 | return (!key && (!secret || !password)) 79 | ? (inquirer.prompt(prompt)) 80 | : { key, secret, password, username: key }; 81 | } 82 | 83 | export function getEnvironment(options: Options) { 84 | return { 85 | prod: options.parent.prod || (!options.parent.testnet && false), 86 | brokerId: parseInt(options.parent.brokerId), 87 | }; 88 | } 89 | 90 | export default function () { 91 | program 92 | .version(version, '-v, --version') 93 | .option('--key ', 'API Key') 94 | .option('--secret ', 'API Secret') 95 | .option('--credentials ', 'path to dotenv file') 96 | .option('-b, --brokerId ', 'Broker ID') 97 | .option('-p, --prod', 'Use the production environment') 98 | .option('-t, --testnet', 'Use the testnet environment'); 99 | 100 | program 101 | .command('connect') 102 | .description('Start websocket interactive environment') 103 | .action(dispatchInteractive); 104 | 105 | program 106 | .command('ticker') 107 | .description('Request ticker') 108 | .option('-c, --currency ', 'Currency of the endpoint') 109 | .action(dispatch); 110 | 111 | program 112 | .command('orderbook') 113 | .description('Request orderbook') 114 | .option('-c, --currency ', 'Currency of the endpoint') 115 | .action(dispatch); 116 | 117 | program 118 | .command('trades') 119 | .description('Request trade history') 120 | .option('-c, --currency ', 'Currency of the endpoint') 121 | .option('-l, --limit ', 'Limit of trades to be returned') 122 | .option('-s, --since ', 'Trade ID used to paginate') 123 | .action(dispatch); 124 | 125 | program 126 | .command('balance') 127 | .description('Request balance') 128 | .action(auth(dispatch)); 129 | 130 | program 131 | .command('requestDeposit') 132 | .description('Request deposit') 133 | .option('-v, --value ', 'Amount value of the deposit, in case of fiat') 134 | .option('-c, --currency ', 'Currency of the deposit .eg: BRL, BTC') 135 | .option('-m, --method ', 'Method ID of the deposit') 136 | .action(auth(dispatch)); 137 | 138 | program 139 | .command('requestDepositList') 140 | .description('Request deposit list') 141 | .option('--page ', 'Pagination offset') 142 | .option('--pageSize ', 'Pagination size') 143 | .option('--status ', 'all, unconfirmed, pending, inprogress, completed, cancelled') 144 | .action(auth(dispatch)); 145 | 146 | program 147 | .command('requestWithdraw') 148 | .description('Request withdraw') 149 | .option('-a, --amount ', 'Amount to withdrawal') 150 | .option('-c, --currency ', 'Currency of the withdraw .eg: BRL, BTC') 151 | .option('-m, --method ', 'Method of the withdraw .eg: bitcoin, bank_name') 152 | .option('-d, --data ', 'Dynamic data represented by a json stringified eg: "{AccountNumber: 99999-9, AccountBranch: 001}"') 153 | .action(auth(dispatch)); 154 | 155 | program 156 | .command('requestWithdrawList') 157 | .description('Request withdraw list') 158 | .option('--page ', 'Pagination offset') 159 | .option('--pageSize ', 'Pagination size') 160 | .option('--status ', 'all, unconfirmed, pending, inprogress, completed, cancelled') 161 | .action(auth(dispatch)); 162 | 163 | program 164 | .command('confirmWithdraw') 165 | .description('Confirm a withdraw request') 166 | .option('--id ', 'Withdraw ID to confirm') 167 | .option('--token ', 'Confirmation token sent by email') 168 | .option('--secondFactor ', 'Second factor token') 169 | .action(auth(dispatch)); 170 | 171 | program 172 | .command('cancelWithdraw') 173 | .description('Cancel a withdraw request') 174 | .option('--id ', 'Withdraw ID to cancel') 175 | .action(auth(dispatch)); 176 | 177 | program 178 | .command('requestLedger') 179 | .description('Request Ledger') 180 | .option('--page ', 'Pagination offset') 181 | .option('--pageSize ', 'Pagination size') 182 | .action(auth(dispatch)); 183 | 184 | program 185 | .command('requestBrokerList') 186 | .description('Request Broker List') 187 | .action(auth(dispatch)); 188 | 189 | program 190 | .command('myOrders') 191 | .description('List order history') 192 | .option('--status ', 'open, filled or cancelled') 193 | .option('--page ', 'Pagination offset') 194 | .option('--pageSize ', 'Pagination size') 195 | .action(auth(dispatch)); 196 | 197 | program 198 | .command('sendOrder') 199 | .description('Place an order') 200 | .option('--type ', 'Order type e.g: MARKET, LIMIT, STOP, STOP_LIMIT') 201 | .option('--side ', 'Order side, e.g: BUY, SELL') 202 | .option('--price ', 'Order price, e.g: 6000') 203 | .option('--amount ', 'Order amount, e.g: 0.1') 204 | .option('--stopPrice ', 'Stop price in case of STOP or STOP_LIMIT order type') 205 | .option('--symbol ', 'Required symbol, e.g.: BTCBRL') 206 | .option('--postOnly', 'Ensures the order will never be executed') 207 | .option('--clientId', 'Optional client id') 208 | .action(auth(dispatch)); 209 | 210 | program 211 | .command('cancelOrder') 212 | .description('Cancel an order') 213 | .option('--orderId ', 'Order ID of the order to be cancelled') 214 | .option('--clientId ', 'Client ID of the order to be cancelled') 215 | .action(auth(dispatch)); 216 | 217 | program.parse(process.argv); 218 | 219 | if (!program.args.length) { 220 | program.help(); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /bin/prompts.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import type { OrderType } from '../src/types'; 3 | 4 | export const promptMenu = (logged: boolean) => [{ 5 | type: 'list', 6 | name: 'action', 7 | pageSize: 20, 8 | message: 'Choose an action', 9 | choices: !logged ? ['login'] : [ 10 | 'heartbeat', 11 | 'balance', 12 | 'requestDeposit', 13 | 'requestDepositList', 14 | 'requestWithdraw', 15 | 'requestWithdrawList', 16 | 'confirmWithdraw', 17 | 'cancelWithdraw', 18 | 'myOrders', 19 | 'requestLedger', 20 | 'sendOrder', 21 | 'cancelOrder', 22 | 'logout', 23 | ], 24 | }]; 25 | 26 | export const promptLogin = [{ 27 | type: 'input', 28 | name: 'username', 29 | message: 'API Key', 30 | }, { 31 | type: 'password', 32 | name: 'password', 33 | message: 'API Password', 34 | }]; 35 | 36 | export const promptRest = [{ 37 | type: 'input', 38 | name: 'key', 39 | message: 'API Key', 40 | }, { 41 | type: 'password', 42 | name: 'secret', 43 | message: 'API Secret', 44 | }]; 45 | 46 | export const promptStatus = [{ 47 | type: 'list', 48 | name: 'status', 49 | message: 'Choose an status', 50 | choices: [ 51 | 'All', 52 | 'Unconfirmed', 53 | 'Pending', 54 | 'InProgress', 55 | 'Completed', 56 | 'Cancelled', 57 | ], 58 | }]; 59 | 60 | export const promptCurrency = [{ 61 | type: 'input', 62 | name: 'currency', 63 | message: 'Currency (BRL, BTC)', 64 | }]; 65 | 66 | export const promptMethod = [{ 67 | type: 'input', 68 | name: 'method', 69 | message: 'Method', 70 | }]; 71 | 72 | export const promptDepositRequest = [{ 73 | type: 'input', 74 | name: 'amount', 75 | message: 'Amount Value', 76 | }, { 77 | type: 'input', 78 | name: 'method', 79 | message: 'Method ID', 80 | }]; 81 | 82 | export const promptWithdrawRequest = [{ 83 | type: 'input', 84 | name: 'amount', 85 | message: 'Amount Value', 86 | }, { 87 | type: 'input', 88 | name: 'data', 89 | message: 'Data Fields', 90 | }, { 91 | type: 'input', 92 | name: 'memo', 93 | message: 'Memo', 94 | }]; 95 | 96 | export const promptOrderHistory = [{ 97 | type: 'list', 98 | name: 'filter', 99 | message: 'Choose an status', 100 | choices: [ 101 | 'all', 102 | 'open', 103 | 'filled', 104 | 'cancelled', 105 | ], 106 | }]; 107 | 108 | export const promptOrderType = [{ 109 | type: 'list', 110 | name: 'type', 111 | message: 'Order type', 112 | choices: [ 113 | 'MARKET', 114 | 'LIMIT', 115 | 'STOP', 116 | 'STOP_LIMIT', 117 | ], 118 | }]; 119 | 120 | export const promptSendOrder = (type: OrderType) => { 121 | const data = [{ 122 | type: 'list', 123 | name: 'side', 124 | message: 'Buy or Sell', 125 | choices: ['BUY', 'SELL'], 126 | }, { 127 | type: 'input', 128 | name: 'amount', 129 | message: 'Amount', 130 | }]; 131 | 132 | if (type === 'STOP' || type === 'STOP_LIMIT') { 133 | data.push({ 134 | type: 'input', 135 | name: 'stopPrice', 136 | message: 'Stop Price', 137 | }); 138 | } 139 | 140 | if (type !== 'MARKET' && type !== 'STOP') { 141 | data.push({ 142 | type: 'input', 143 | name: 'price', 144 | message: 'Price', 145 | }); 146 | } 147 | 148 | data.push({ 149 | type: 'input', 150 | name: 'symbol', 151 | message: 'Symbol', 152 | }); 153 | 154 | if (type === 'LIMIT') { 155 | data.push({ 156 | type: 'confirm', 157 | name: 'postOnly', 158 | message: 'Post Only?', 159 | default: false, 160 | }); 161 | } 162 | 163 | return data; 164 | }; 165 | 166 | export const promptCancelOrder = [{ 167 | type: 'input', 168 | name: 'orderId', 169 | message: 'Order ID', 170 | }, { 171 | type: 'input', 172 | name: 'clientId', 173 | message: 'Client ID', 174 | }]; 175 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Running Examples 2 | 3 | 4 | ## Node 5 | 6 | `$ node balance.js ` 7 | 8 | ## Browser 9 | 10 | Install webpack 11 | 12 | `$ npm install` 13 | `$ npm run webpack` 14 | 15 | And open index.html on the browser. 16 | -------------------------------------------------------------------------------- /examples/authWebSocket.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | console.log(logged); 9 | }).catch(function(err) { 10 | console.log(err); 11 | }); 12 | -------------------------------------------------------------------------------- /examples/balance.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | return blinktrade.balance(); 9 | }).then(function(balance) { 10 | console.log('Balance', balance); 11 | }).catch(function(err) { 12 | console.log(err); 13 | }); 14 | -------------------------------------------------------------------------------- /examples/deposits.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | return blinktrade.requestDeposit(); 9 | }).then(function(deposit) { 10 | console.log('\nBitcoin Deposit \n', deposit); 11 | return blinktrade.requestDeposit({ 12 | value: parseInt(200 * 1e8), 13 | currency: 'BRL', 14 | depositMethodId: 502, 15 | }); 16 | }).then(function(deposit) { 17 | console.log('\nFiat Deposit \n', deposit); 18 | }).catch(function(err) { 19 | console.log(err); 20 | }); 21 | -------------------------------------------------------------------------------- /examples/eventEmitters.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | function onBalanceUpdate(newBalance) { 6 | console.log('Balance Updated', newBalance); 7 | } 8 | 9 | function onExecutionReportNew(data) { 10 | console.log('EXECUTION_REPORT:NEW', data); 11 | } 12 | function onExecutionReportPartial(data) { 13 | console.log('EXECUTION_REPORT:PARTIAL', data); 14 | } 15 | function onExecutionReportExecution(data) { 16 | console.log('EXECUTION_REPORT:EXECUTION', data); 17 | } 18 | function onExecutionReportCanceled(data) { 19 | console.log('EXECUTION_REPORT:CANCELED', data); 20 | } 21 | function onExecutionReportRejected(data) { 22 | console.log('EXECUTION_REPORT:REJECTED', data); 23 | } 24 | 25 | function onOrderBookNewOrder(data) { 26 | console.log('OB:NEW_ORDER', data); 27 | } 28 | function onOrderBookUpdateOrder(data) { 29 | console.log('OB:UPDATE_ORDER', data); 30 | } 31 | function onOrderBookDeleteOrder(data) { 32 | console.log('OB:DELETE_ORDER', data); 33 | } 34 | function onOrderBookDeleteThruOrder(data) { 35 | console.log('OB:DELETE_ORDERS_THRU', data); 36 | } 37 | function onOrderBookTradeNew(data) { 38 | console.log('OB:TRADE_NEW', data); 39 | } 40 | 41 | function onAnyTicker(data) { 42 | console.log('Any Ticker Updated'); 43 | } 44 | 45 | function onBTCBRL(data) { 46 | console.log('BTCBRL', data); 47 | } 48 | 49 | blinktrade.connect().then(function() { 50 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 51 | }).then(function(logged) { 52 | return blinktrade.balance().on('BALANCE', onBalanceUpdate); 53 | }).then(function(balance) { 54 | console.log('Balance', balance); 55 | 56 | blinktrade.executionReport() 57 | .on('EXECUTION_REPORT:NEW', onExecutionReportNew) 58 | .on('EXECUTION_REPORT:PARTIAL', onExecutionReportPartial) 59 | .on('EXECUTION_REPORT:EXECUTION', onExecutionReportExecution) 60 | .on('EXECUTION_REPORT:CANCELED', onExecutionReportCanceled) 61 | .on('EXECUTION_REPORT:REJECTED', onExecutionReportRejected); 62 | 63 | 64 | return blinktrade.subscribeMarketData(['BTCBRL']) 65 | .on('OB:NEW_ORDER', onOrderBookNewOrder) 66 | .on('OB:UPDATE_ORDER', onOrderBookUpdateOrder) 67 | .on('OB:DELETE_ORDER', onOrderBookDeleteOrder) 68 | .on('OB:DELETE_ORDERS_THRU', onOrderBookDeleteThruOrder) 69 | .on('OB:TRADE_NEW', onOrderBookTradeNew); 70 | 71 | }).then(function(orderbook) { 72 | 73 | return blinktrade.subscribeTicker(['BLINK:BTCBRL']) 74 | .on('BLINK:*', onAnyTicker) 75 | .on('BLINK:BTCBRL', onBTCBRL) 76 | .many('BLINK:BTCBRL', 2, onBTCBRL); 77 | }).then(function(ticker) { 78 | return blinktrade.sendOrder({ 79 | side: '1', 80 | price: parseInt(10 * 1e8, 10), 81 | amount: parseInt(0.05 * 1e8, 10), 82 | symbol: 'BTCBRL', 83 | }); 84 | }).then(function(order) { 85 | return blinktrade.cancelOrder({ 86 | orderId: order.OrderID, 87 | clientId: order.ClOrdID 88 | }); 89 | }).catch(function(err) { 90 | console.log(err); 91 | }); 92 | -------------------------------------------------------------------------------- /examples/executionReport.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | function onNew(data) { 6 | console.log('New Order Received', data); 7 | } 8 | function onPartial(data) { 9 | console.log('Order Partially Executed', data); 10 | } 11 | function onExecution(data) { 12 | console.log('Order Executed', data); 13 | } 14 | function onCanceled(data) { 15 | console.log('Order Canceled', data); 16 | } 17 | function onRejected(data) { 18 | console.log('Order Rejected', data); 19 | } 20 | 21 | blinktrade.connect().then(function() { 22 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 23 | }).then(function(logged) { 24 | blinktrade.executionReport() 25 | .on('EXECUTION_REPORT:NEW', onNew) 26 | .on('EXECUTION_REPORT:PARTIAL', onPartial) 27 | .on('EXECUTION_REPORT:EXECUTION', onExecution) 28 | .on('EXECUTION_REPORT:CANCELED', onCanceled) 29 | .on('EXECUTION_REPORT:REJECTED', onRejected); 30 | 31 | return blinktrade.sendOrder({ 32 | side: '1', 33 | price: parseInt(10 * 1e8, 10), 34 | amount: parseInt(0.05 * 1e8, 10), 35 | symbol: 'BTCBRL', 36 | }); 37 | }).then(function(order) { 38 | // Cancel order after 5 seconds 39 | setTimeout(function() { 40 | return blinktrade.cancelOrder({ orderId: order.OrderID, clientId: order.ClOrdID }); 41 | }, 5000) 42 | }).catch(function(err) { 43 | console.log(err); 44 | }); 45 | -------------------------------------------------------------------------------- /examples/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | BlinkTradeJS on the browser 6 | 7 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /examples/myOrders.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | return blinktrade.myOrders(); 9 | }).then(function(orders) { 10 | console.log(orders); 11 | }).catch(function(err) { 12 | console.log(err); 13 | }); 14 | -------------------------------------------------------------------------------- /examples/orderBookWebSocket.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.subscribeMarketData(['BTCBRL']) 7 | }).then(function(orderbook) { 8 | console.log(orderbook); 9 | }).catch(function(err) { 10 | console.log(err); 11 | }); 12 | -------------------------------------------------------------------------------- /examples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "blinktrade-js-example", 3 | "version": "1.0.0", 4 | "private": true, 5 | "description": "BlinkTradeJS example", 6 | "main": "bundle-node.js", 7 | "scripts": { 8 | "build": "rm -rf node_modules/blinktrade && npm install", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "dependencies": { 12 | "blinktrade": "../" 13 | }, 14 | "author": "Cesar Augusto", 15 | "license": "GPL-3.0" 16 | } 17 | -------------------------------------------------------------------------------- /examples/publicRest.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | 3 | var BlinkTradeRest = require('blinktrade').BlinkTradeRest; 4 | 5 | var BlinkTrade = new BlinkTradeRest({ 6 | prod: true, 7 | brokerId: 4, 8 | currency: 'BRL', 9 | }); 10 | 11 | BlinkTrade.ticker().then(function(data) { 12 | console.log('Ticker', data); 13 | }); 14 | BlinkTrade.orderbook().then(function(data) { 15 | console.log('OrderBook', data.pair, 'Bids:', data.bids.length, 'Asks:', data.asks.length); 16 | }); 17 | BlinkTrade.trades({ limit: 100, since: 2487 }).then(function(data) { 18 | console.log('Trades', data.length); 19 | }); 20 | -------------------------------------------------------------------------------- /examples/requestDepositList.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | return blinktrade.requestDepositList() 9 | }).then(function(deposits) { 10 | console.log('Deposits', deposits); 11 | }).catch(function(err) { 12 | console.log(err); 13 | }); 14 | 15 | -------------------------------------------------------------------------------- /examples/requestWithdrawList.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | return blinktrade.requestWithdrawList() 9 | }).then(function(withdraws) { 10 | console.log('Withdraws', withdraws.WithdrawListGrp); 11 | }).catch(function(err) { 12 | console.log(err); 13 | }); 14 | -------------------------------------------------------------------------------- /examples/sendAndCancelOrdersRest.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeRest = require('blinktrade').BlinkTradeRest; 2 | 3 | var blinktrade = new BlinkTradeRest({ 4 | prod: false, 5 | key: 'Ya8EkJ1kJSLyt5ZX60aWlmA7zPEgBqajt7UmvCZEvaA', 6 | secret: 'xUS4e9hEl1RGpj4Fmh4KvQYKMWT2yItG9SGlDx4aYfo', 7 | currency: 'BRL', 8 | }); 9 | 10 | blinktrade.sendOrder({ 11 | side: '1', 12 | price: parseInt(100 * 1e8, 10), 13 | amount: parseInt(0.05 * 1e8, 10), 14 | symbol: 'BTCBRL', 15 | }).then(function(order) { 16 | console.log(order); 17 | console.log('Cancelling order: #' + order[0].OrderID); 18 | return blinktrade.cancelOrder({ orderId: order[0].OrderID, clientId: order[0].ClOrdID }); 19 | }).then(function(order) { 20 | console.log(order); 21 | console.log('Order: #' + order[0].OrderID + ' cancelled'); 22 | }).catch(function(err) { 23 | console.log(err); 24 | }); 25 | 26 | -------------------------------------------------------------------------------- /examples/sendAndCancelOrdersWebSocket.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function() { 8 | return blinktrade.sendOrder({ 9 | side: '1', 10 | price: parseInt(550 * 1e8, 10), 11 | amount: parseInt(0.05 * 1e8, 10), 12 | symbol: 'BTCBRL', 13 | }); 14 | }).then(function(order) { 15 | console.log(order); 16 | console.log('Cancelling order: #' + order.OrderID); 17 | return blinktrade.cancelOrder({ orderId: order.OrderID, clientId: order.ClOrdID }); 18 | }).then(function(order) { 19 | console.log('Order: #' + order.OrderID + ' cancelled'); 20 | }).catch(function(err) { 21 | console.log(err); 22 | }); 23 | -------------------------------------------------------------------------------- /examples/tickerWebSocket.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.subscribeTicker(['BLINK:BTCBRL']) 7 | }).then(function(ticker) { 8 | console.log(ticker); 9 | }).catch(function(err) { 10 | console.log(err); 11 | }); 12 | -------------------------------------------------------------------------------- /examples/tradeHistory.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.tradeHistory(); 7 | }).then(function(trades) { 8 | console.log(trades); 9 | }).catch(function(err) { 10 | console.log(err); 11 | }); 12 | -------------------------------------------------------------------------------- /examples/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "noImplicitAny": false, 6 | "sourceMap": false 7 | }, 8 | "exclude": [ 9 | "node_modules" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /examples/typescript.ts: -------------------------------------------------------------------------------- 1 | import { BlinkTradeRest, BlinkTradeWS } from 'blinktrade'; 2 | 3 | let blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | console.log('WebSocket Connected'); 7 | return blinktrade.heartbeat(); 8 | }).then(function(heartbeat) { 9 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 10 | }).then(function(login) { 11 | console.log('Logged', login); 12 | return blinktrade.profile(); 13 | }).then(function(profile) { 14 | console.log('My Profile', profile); 15 | 16 | return blinktrade.subscribeTicker(['BLINK:BTCBRL']) 17 | .on('BLINK:BTCBRL', function(data) { 18 | console.log('Ticker Updated', data); 19 | }); 20 | }).then(function(ticker) { 21 | 22 | console.log('Ticker', ticker); 23 | return blinktrade.subscribeOrderbook(['BTCBRL']) 24 | .on('OB:NEW_ORDER', (data) => { 25 | console.log('OB:NEW_ORDER', data); 26 | }).on('OB:UPDATE_ORDER', (data) => { 27 | console.log('OB:UPDATE_ORDER', data); 28 | }).on('OB:DELETE_ORDER', (data) => { 29 | console.log('OB:DELETE_ORDER', data); 30 | }).on('OB:DELETE_ORDERS_THRU', (data) => { 31 | console.log('OB:DELETE_ORDERS_THRU', data); 32 | }).on('OB:TRADE_NEW', (data) => { 33 | console.log('OB:TRADE_NEW', data); 34 | }); 35 | 36 | }).then(function(marketData) { 37 | console.log('OrderBook FULL REFRESH'); 38 | console.log(marketData.MDFullGrp.BTCBRL); 39 | return blinktrade.balance() 40 | .on('BALANCE', (data) => { 41 | console.log('Balance Updated', data); 42 | }); 43 | }).then(function(balance) { 44 | blinktrade.executionReport() 45 | .on('EXECUTION_REPORT:NEW', (data) => { 46 | console.log('EXECUTION_REPORT:NEW', data); 47 | }).on('EXECUTION_REPORT:PARTIAL', (data) => { 48 | console.log('EXECUTION_REPORT:PARTIAL', data); 49 | }).on('EXECUTION_REPORT:EXECUTION', (data) => { 50 | console.log('EXECUTION_REPORT:EXECUTION', data); 51 | }).on('EXECUTION_REPORT:CANCELED', (data) => { 52 | console.log('EXECUTION_REPORT:CANCELED', data); 53 | }).on('EXECUTION_REPORT:REJECTED', (data) => { 54 | console.log('EXECUTION_REPORT:REJECTED', data); 55 | }); 56 | 57 | return blinktrade.sendOrder({ 58 | side: '1', 59 | price: parseInt((550 * 1e8).toFixed(0), 10), 60 | amount: parseInt((0.05 * 1e8).toFixed(0), 10), 61 | symbol: 'BTCBRL', 62 | }); 63 | }).then(function(order) { 64 | console.log('Cancelling order'); 65 | return blinktrade.cancelOrder({ orderId: order.OrderID, clientId: order.ClOrdID }); 66 | }).then(function(order) { 67 | return blinktrade.myOrders(); 68 | }).then(function(myOrders) { 69 | console.log('My Orders', myOrders); 70 | return blinktrade.tradeHistory(); 71 | }).then(function(trades) { 72 | console.log('Trade History', trades); 73 | return blinktrade.logout(); 74 | }).then(function(logout) { 75 | console.log('Logout'); 76 | }).catch(function(err) { 77 | console.log('Error', err); 78 | }); 79 | -------------------------------------------------------------------------------- /examples/withdraw.js: -------------------------------------------------------------------------------- 1 | var BlinkTradeWS = require('blinktrade').BlinkTradeWS; 2 | 3 | var blinktrade = new BlinkTradeWS(); 4 | 5 | blinktrade.connect().then(function() { 6 | return blinktrade.login({ username: 'rodrigo', password: 'abc12345' }); 7 | }).then(function(logged) { 8 | return blinktrade.requestWithdraw({ 9 | amount: parseInt(200 * 1e8), 10 | currency: 'BRL', 11 | method: 'Paypal', 12 | data: { 13 | Email: 'user@blinktrade.com' 14 | } 15 | }); 16 | }).then(function(withdraw) { 17 | console.log('\nFIAT Withdraw: \n', withdraw); 18 | return blinktrade.requestWithdraw({ 19 | amount: parseInt(0.5 * 1e8), 20 | currency: 'BTC', 21 | method: 'bitcoin', 22 | data: { 23 | Wallet: '1KdEQfoxxgfgV1GkGb9JBX1F9fiaCqZdgV' 24 | } 25 | }); 26 | }).then(function(withdraw) { 27 | console.log('\nBitcoin Withdraw: \n', withdraw); 28 | }).catch(function(err) { 29 | console.log(err); 30 | }); 31 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export type BlinkTradeParams = { 2 | url?: string; 3 | prod?: boolean; 4 | brokerId?: number; 5 | transport?: any; 6 | level?: BlinkTradeLevel; 7 | }; 8 | 9 | export type BlinkTradeLevel = 0 | 2; 10 | export type BlinkTradeCurrencies = | 'USD' | 'BRL' | 'CLP' | 'VND'; 11 | 12 | export type BlinkTradeRestTransport = { 13 | fetchPublic: (string) => Promise; 14 | fetchTrade: (msg: Message) => Promise; 15 | }; 16 | 17 | export type BlinkTradeRestParams = { 18 | key?: string; 19 | secret?: string; 20 | currency?: BlinkTradeCurrencies; 21 | transport?: BlinkTradeRestTransport; 22 | } & BlinkTradeParams; 23 | 24 | export type BlinkTradeWSTransport = { 25 | connect: (callback?: Function) => Promise; 26 | disconnect: () => void; 27 | sendMessage: (msg: Message) => void; 28 | sendMessageAsPromise: (msg: Message) => Promise; 29 | emitterPromise?: (promise: any, callback?: Function) => PromiseEmitter; 30 | eventEmitter: any; 31 | }; 32 | 33 | export type BlinkTradeWSParams = { 34 | headers?: AnyObject; 35 | fingerPrint?: string; 36 | reconnect?: boolean; 37 | reconnectInterval?: number; 38 | transport?: BlinkTradeWSTransport; 39 | } & BlinkTradeParams; 40 | 41 | export type MarketDataParams = Array | { 42 | instruments: Array; 43 | columns?: Array; 44 | entryTypes?: Array<0 | 1 | 2>; 45 | marketDepth?: number; 46 | level?: BlinkTradeLevel; 47 | }; 48 | 49 | export type Message = { 50 | MsgType: string; 51 | } & AnyObject; 52 | 53 | export type AnyObject = { 54 | [key: string]: any; 55 | }; 56 | 57 | export type StatusListType = '1' | '2' | '4' | '8'; 58 | export type OrderSide = 'BUY' | 'SELL' | '1' | '2'; 59 | export type OrderType = 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_LIMIT'; 60 | 61 | export type Pagination = { 62 | page?: number; 63 | pageSize?: number; 64 | }; 65 | 66 | export type DepositWithdrawList = { 67 | /** 68 | * [ADMIN] Optional id of a customer 69 | */ 70 | clientId?: string, 71 | 72 | 73 | /** 74 | * Array of filters 75 | */ 76 | filter?: Array, 77 | /** 78 | * 1-Pending, 2-In Progress, 4-Completed, 8-Cancelled 79 | */ 80 | status?: Array, 81 | } & Pagination 82 | 83 | export class BlinkTradeTrade { 84 | constructor(props: BlinkTradeParams); 85 | 86 | /** 87 | * Request balance. 88 | * 89 | * @Events: `BALANCE` 90 | */ 91 | balance(clientId?: number, callback?: Function): Promise; 92 | 93 | /** 94 | * Returns your open orders 95 | */ 96 | myOrders(param?: Pagination & { 97 | /** 98 | * All: [] 99 | * Open Orders: filter: ["has_leaves_qty eq 1"] 100 | * Filled Orders: filter: ["has_cum_qty eq 1"] 101 | * Cancelled Orders: filter: ["has_cxl_qty eq 1"] 102 | */ 103 | filter?: Array 104 | }, callback?: Function): Promise; 105 | 106 | /** 107 | * Send an order 108 | */ 109 | sendOrder(params: { 110 | /** 111 | * "BUY", "SELL or "1" = BUY, "2" = SELL 112 | */ 113 | side: OrderSide, 114 | 115 | /** 116 | * Order type, defaults to LIMIT 117 | */ 118 | type?: OrderType, 119 | 120 | /** 121 | * Price in "satoshis". e.g.: 1800 * 1e8 122 | */ 123 | price?: number, 124 | 125 | /** 126 | * Stop price 127 | */ 128 | stopPrice?: number, 129 | 130 | /** 131 | * Amount to be sent in satoshis. e.g.: 0.5 * 1e8 132 | */ 133 | amount: number, 134 | 135 | /** 136 | * Currency pair symbol, check symbols table 137 | */ 138 | symbol: string, 139 | 140 | /** 141 | * Optional ClientID 142 | */ 143 | clientId?: string, 144 | 145 | /** 146 | * If true, ensures that your order will be added to the order book and not match with a existing order 147 | */ 148 | postOnly?: boolean, 149 | }, callback?: Function): Promise; 150 | 151 | /** 152 | * Cancel an order 153 | */ 154 | cancelOrder(param?: number | { 155 | /** 156 | * Required Order ID to be canceled 157 | */ 158 | orderId?: number; 159 | 160 | /** 161 | * You need to pass the clientId (ClOrdID) in order to get a response 162 | */ 163 | clientId?: string; 164 | 165 | /** 166 | * Cancell all orders of the side 167 | */ 168 | side?: OrderSide; 169 | }, callback?: Function): Promise; 170 | 171 | /** 172 | * Returns a list of your withdraws 173 | */ 174 | requestWithdrawList(params: DepositWithdrawList, callback?: Function): Promise; 175 | 176 | /** 177 | * Request a FIAT or bitcoin withdraw 178 | */ 179 | requestWithdraw(params: { 180 | /** 181 | * Withdraw required fields 182 | */ 183 | data: AnyObject; 184 | 185 | /** 186 | * Amount of the withdraw 187 | */ 188 | amount: number; 189 | 190 | /** 191 | * Method name of withdraw, check with your broker, defaults to bitcoin 192 | */ 193 | method?: string; 194 | 195 | /** 196 | * Currency pair symbol to withdraw, defaults to `BTC` 197 | */ 198 | currency?: string; 199 | }, callback?: Function): Promise; 200 | 201 | /** 202 | * Confirm withdraw to two factor authentication 203 | */ 204 | confirmWithdraw(params: { 205 | /** 206 | * Withdraw ID to confirm 207 | */ 208 | withdrawId: string; 209 | 210 | /** 211 | * Confirmation Token sent by email 212 | */ 213 | confirmationToken?: string; 214 | 215 | /** 216 | * Second Factor Authentication code generated by authy 217 | */ 218 | secondFactor?: string; 219 | }, callback?: Function): Promise; 220 | 221 | /** 222 | * Cancel withdraw 223 | */ 224 | cancelWithdraw(withdrawId: number, callback?: Function): Promise; 225 | 226 | /** 227 | * Returns a list of your deposits 228 | */ 229 | requestDepositList(params: DepositWithdrawList, callback?: Function): Promise; 230 | 231 | /** 232 | * If any arguments was provied, it will generate a bitcoin deposit along with the address. 233 | */ 234 | requestDeposit(params: { 235 | /** 236 | * Value amount to deposit 237 | */ 238 | value?: number; 239 | 240 | /** 241 | * Currency pair symbol to withdraw, defaults to `BTC` 242 | */ 243 | currency?: string; 244 | 245 | /** 246 | * Method ID to deposit, check `requestDepositMethods` 247 | */ 248 | depositMethodId?: number; 249 | }, callback?: Function): Promise; 250 | 251 | /** 252 | * Used to check the deposit methods codes to FIAT deposit 253 | */ 254 | requestDepositMethods(callback?: Function): Promise; 255 | 256 | /** 257 | * Request Ledger 258 | */ 259 | requestLedger(params?: Pagination & { 260 | /** 261 | * Currency available on the current broker e.g.: `BTC`, `BRL`, `PKR`, `CLP`. 262 | * Only one currency is supported on the request. 263 | */ 264 | currency: string; 265 | }, callback?: Function): Promise; 266 | } 267 | 268 | export class BlinkTradeRest extends BlinkTradeTrade { 269 | constructor(props: BlinkTradeRestParams); 270 | /** 271 | * Ticker is a summary information about the current status of an exchange. 272 | */ 273 | ticker(callback?: Function): Promise; 274 | 275 | /** 276 | * A list of the last trades executed on an exchange since a chosen date. 277 | */ 278 | trades(trades?: { 279 | /** 280 | * Limit of trades that will be returned. should be a positive integer. Optional; defaults to 1000 trades. 281 | */ 282 | limit?: number; 283 | 284 | /** 285 | * TradeID which must be fetched from. Optional; 286 | */ 287 | since?: number; 288 | }, callback?: Function): Promise; 289 | 290 | /** 291 | * Order book is a list of orders that shows the interest of buyers (bids) and sellers (asks). 292 | */ 293 | orderbook(callback?: Function): Promise; 294 | } 295 | 296 | export class BlinkTradeWS extends BlinkTradeTrade { 297 | constructor(props: BlinkTradeWSParams); 298 | connect: (callback?: Function) => Promise; 299 | disconnect: () => any; 300 | heartbeat: (callback?: Function) => Promise; 301 | login: (params: { 302 | /** 303 | * Account username or an API Key 304 | */ 305 | username: string; 306 | 307 | /** 308 | * Password or an API Password 309 | */ 310 | password: string; 311 | 312 | /** 313 | * Optional secondFactor, if the authentication require second factor, you'll receive an error with NeedSecondFactor = true 314 | */ 315 | secondFactor?: string; 316 | 317 | /** 318 | * Cancel all orders sent by the session when the websocket disconnects 319 | */ 320 | cancelOnDisconnect?: boolean; 321 | 322 | /** 323 | * Optional brokerId 324 | */ 325 | brokerId?: number; 326 | }) => Promise; 327 | /** 328 | * Logout session from the server, the connection still connected. 329 | */ 330 | logout(callback?: Function): Promise; 331 | 332 | /** 333 | * Request balance. 334 | * 335 | * @Events: `BALANCE` 336 | */ 337 | balance(clientId?: number, callback?: Function): PromiseEmitter; 338 | 339 | /** 340 | * Returns profile information 341 | */ 342 | profile(callback?: Function): Promise; 343 | 344 | /** 345 | * @Events: Any symbol subscribed 346 | */ 347 | subscribeTicker(symbols: Array, callback?: Function): PromiseEmitter; 348 | 349 | /** 350 | * Unsubscribe ticker 351 | */ 352 | unSubscribeTicker(SecurityStatusReqID: number): number; 353 | 354 | /** 355 | * Subscribe to orderbook 356 | */ 357 | subscribeOrderbook(options: MarketDataParams, callback?: Function): PromiseEmitter; 358 | 359 | /** 360 | * get orderbook synced 361 | */ 362 | syncOrderBook(options: MarketDataParams, callback?: Function): Promise; 363 | 364 | /** 365 | * Unsubscribe from orderbook 366 | */ 367 | unSubscribeOrderbook(MDReqID: number): number; 368 | 369 | /** 370 | * @Events: 371 | * `EXECUTION_REPORT:NEW` => Callback when you send a new order 372 | * `EXECUTION_REPORT:PARTIAL` => Callback when your order have been partialy executed 373 | * `EXECUTION_REPORT:EXECUTION` => Callback when an order have been sussefully executed 374 | * `EXECUTION_REPORT:CANCELED` => Callback when your order have been canceled 375 | * `EXECUTION_REPORT:REJECTED` => Callback when your order have been rejected 376 | */ 377 | executionReport(callback?: Function): PromiseEmitter; 378 | 379 | /** 380 | * A list of the last trades executed in the last 24 hours. 381 | */ 382 | tradeHistory(params?: Pagination & { 383 | /** 384 | * TradeID or Date which executed trades must be fetched from. is in Unix Time date format. Optional; defaults to the date of the first executed trade. 385 | */ 386 | since?: number; 387 | 388 | /** 389 | * List os symbols to be returned 390 | */ 391 | symbols?: Array; 392 | }, callback?: Function): Promise; 393 | 394 | /** 395 | * Callbacks on each deposit update, note that using as promise will only returned once. 396 | */ 397 | onDepositRefresh(callback?: Function): Promise 398 | 399 | /** 400 | * Callbacks on each withdraw update, note that using as promise will only returned once. 401 | */ 402 | onWithdrawRefresh(callback?: Function): Promise 403 | } 404 | 405 | 406 | export type PromiseEmitter = Promise & { 407 | on: (event: string, listener: Function) => PromiseEmitter; 408 | onAny: (listener: Function) => PromiseEmitter; 409 | offAny: (listener: Function) => PromiseEmitter; 410 | once: (event: string, listener: Function) => PromiseEmitter; 411 | many: (event: string, times: number, listener: Function) => PromiseEmitter; 412 | removeListener: (event: string, listener: Function) => PromiseEmitter; 413 | removeAllListeners: (events: Array) => PromiseEmitter; 414 | }; 415 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "blinktrade", 3 | "version": "1.0.0-rc.1", 4 | "description": "BlinkTrade client for node.js", 5 | "homepage": "https://blinktrade.com/docs", 6 | "main": "lib/blinktrade.js", 7 | "browser": "dist/blinktrade.js", 8 | "module": "es/blinktrade.js", 9 | "directories": { 10 | "test": "test" 11 | }, 12 | "bin": { 13 | "blinktrade": "bin/blinktrade" 14 | }, 15 | "scripts": { 16 | "lint": "eslint src test", 17 | "flow": "flow", 18 | "check": "yarn lint && yarn test ", 19 | "clean:flow": "find src -type f -name '*.flow' -delete", 20 | "build:es": "cross-env NODE_ENV=es rollup -c -o es/blinktrade.js", 21 | "build:umd": "cross-env NODE_ENV=development rollup -c -o dist/blinktrade.js", 22 | "build:umd:min": "cross-env NODE_ENV=production rollup -c -o dist/blinktrade.min.js", 23 | "build:commonjs": "cross-env NODE_ENV=cjs rollup -c -o lib/blinktrade.js", 24 | "build:cli": "cross-env NODE_ENV=cjs rollup -c -o bin/blinktrade && echo \"#!/usr/bin/env node\\n\\n$(cat bin/blinktrade)\" > bin/blinktrade", 25 | "build:prod": "yarn build:umd:min", 26 | "build:dev": "yarn build:commonjs && yarn build:umd && yarn build:es", 27 | "build:flow:index": "for i in dist lib es; do sed 's/\\./..\\/src/g' src/index.js > $i/blinktrade.js.flow; done", 28 | "build:flow": "for file in $(find ./src -name '*.js' -not -path '*/__mocks__*'); do cp \"$file\" `echo \"$file\" | sed 's/\\/src\\//\\/src\\//g'`.flow; done && yarn build:flow:index", 29 | "build": "yarn build:dev && yarn build:prod && yarn build:cli && yarn build:flow", 30 | "prepare": "yarn build", 31 | "test": "jest", 32 | "test:cov": "jest --coverage", 33 | "test:watch": "jest --watch" 34 | }, 35 | "keywords": [ 36 | "blinktrade", 37 | "node" 38 | ], 39 | "jest": { 40 | "projects": [ 41 | { 42 | "displayName": "browser", 43 | "testEnvironment": "jsdom", 44 | "testMatch": [ 45 | "/test/browser/*" 46 | ] 47 | }, 48 | { 49 | "displayName": "node", 50 | "testEnvironment": "jest-environment-node", 51 | "testMatch": [ 52 | "/test/node/*" 53 | ] 54 | } 55 | ] 56 | }, 57 | "author": "Cesar Augusto, Rodrigo Souza", 58 | "license": "GPLv3", 59 | "dependencies": { 60 | "commander": "^2.19.0", 61 | "dotenv": "^6.1.0", 62 | "eventemitter2": "^5.0.1", 63 | "fetch-ponyfill": "^6.0.2", 64 | "inquirer": "^6.2.0", 65 | "invariant": "^2.2.4", 66 | "ip": "^1.1.3", 67 | "js-sha256": "^0.9.0", 68 | "macaddress-secure": "^0.2.11", 69 | "nodeify": "^1.0.0", 70 | "ws": "^5.1.1" 71 | }, 72 | "devDependencies": { 73 | "@babel/core": "^7.0.0", 74 | "@babel/plugin-external-helpers": "^7.0.0", 75 | "@babel/plugin-proposal-object-rest-spread": "^7.0.0", 76 | "@babel/preset-env": "^7.0.0", 77 | "@babel/preset-flow": "^7.0.0", 78 | "@babel/register": "7.0.0", 79 | "babel-core": "^7.0.0-bridge.0", 80 | "babel-eslint": "^8.0.2", 81 | "babel-jest": "^23.6.0", 82 | "cross-env": "^5.1.1", 83 | "eslint": "^4.11.0", 84 | "eslint-config-airbnb-base": "^12.1.0", 85 | "eslint-plugin-flowtype": "^2.39.1", 86 | "eslint-plugin-import": "^2.8.0", 87 | "flow-bin": "^0.81.0", 88 | "jest": "^23.6.0", 89 | "jest-cli": "^23.6.0", 90 | "nock": "^10.0.1", 91 | "rollup": "^0.66.0", 92 | "rollup-plugin-babel": "^4.0.1", 93 | "rollup-plugin-commonjs": "^9.1.8", 94 | "rollup-plugin-flow": "^1.1.1", 95 | "rollup-plugin-json": "^3.1.0", 96 | "rollup-plugin-node-resolve": "^3.4.0", 97 | "rollup-plugin-shim": "^1.0.0", 98 | "rollup-plugin-uglify": "^6.0.0" 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import json from 'rollup-plugin-json'; 3 | import flow from 'rollup-plugin-flow'; 4 | import babel from 'rollup-plugin-babel'; 5 | import commonjs from 'rollup-plugin-commonjs'; 6 | import resolve from 'rollup-plugin-node-resolve'; 7 | import shim from 'rollup-plugin-shim'; 8 | import { uglify } from 'rollup-plugin-uglify'; 9 | 10 | const env = process.env.NODE_ENV; 11 | const isCLI = process.argv[process.argv.length - 1] === 'bin/blinktrade'; 12 | const format = (env === 'development' || env === 'production') ? 'umd' : env; 13 | 14 | const config = { 15 | input: isCLI ? 'bin/blinktrade.js' : 'src/index.js', 16 | output: { 17 | name: 'blinktrade', 18 | format, 19 | }, 20 | plugins: [ 21 | json({ preferConst: true }), 22 | flow({ all: true }), 23 | resolve({ 24 | jsnext: true, 25 | browser: format === 'umd', 26 | preferBuiltins: false, 27 | }), 28 | commonjs({ 29 | include: 'node_modules/**', 30 | }), 31 | babel({ 32 | babelrc: false, 33 | presets: [['@babel/preset-env', { modules: false }]], 34 | plugins: ['@babel/plugin-proposal-object-rest-spread'], 35 | }), 36 | ], 37 | }; 38 | 39 | if (format === 'umd') { 40 | config.plugins.push(uglify({ 41 | mangle: env === 'production', 42 | output: { 43 | beautify: env !== 'production', 44 | }, 45 | compress: { 46 | pure_getters: true, 47 | unsafe: true, 48 | unsafe_comps: true, 49 | warnings: false, 50 | }, 51 | })); 52 | // Remove modules that can't be bundled on the browser 53 | config.plugins.unshift(shim({ 54 | ws: 'export default {}', 55 | ip: 'export default {}', 56 | dgram: 'export default {}', 57 | os: 'export default {}', 58 | 'macaddress-secure': 'export default {}', 59 | [path.join(__dirname, 'src/util/macaddress')]: 'export function getMac() {}', 60 | [path.join(__dirname, 'src/util/stun')]: ` 61 | export function getStun() {} 62 | export function closeStun() {} 63 | `, 64 | })); 65 | } else { 66 | config.external = ['ws', 'commander', 'inquirer', 'dotenv', '../lib/blinktrade']; 67 | } 68 | 69 | export default config; 70 | -------------------------------------------------------------------------------- /src/constants/actionTypes.js: -------------------------------------------------------------------------------- 1 | export const HEARTBEAT = 'HEARTBEAT'; 2 | 3 | export const BROKER_LIST = 'BROKER_LIST'; 4 | 5 | export const SECURITY_LIST = 'SECURITY_LIST'; 6 | export const SECURITY_STATUS_SUBSCRIBE = 'SECURITY_STATUS_SUBSCRIBE'; 7 | 8 | export const MD_TRADES = 'MD_TRADES'; 9 | export const MD_TRADES_UNSUBSCRIBE = 'MD_TRADES_UNSUBSCRIBE'; 10 | export const MD_INCREMENT = 'MD_INCREMENT'; 11 | export const MD_FULL_REFRESH = 'MD_FULL_REFRESH'; 12 | export const MD_UNSUBSCRIBE = 'MD_UNSUBSCRIBE'; 13 | export const MD_OPENING = 'MD_OPENING'; 14 | 15 | export const OB_NEW_ORDER = 'OB_NEW_ORDER'; 16 | export const OB_UPDATE_ORDER = 'OB_UPDATE_ORDER'; 17 | export const OB_DELETE_ORDER = 'OB_DELETE_ORDER'; 18 | export const OB_DELETE_ORDERS_THRU = 'OB_DELETE_ORDERS_THRU'; 19 | 20 | export const EXECUTION_REPORT = 'EXECUTION_REPORT'; 21 | export const EXECUTION_REPORT_NEW = 'EXECUTION_REPORT_NEW'; 22 | export const EXECUTION_REPORT_PARTIAL = 'EXECUTION_REPORT_PARTIAL'; 23 | export const EXECUTION_REPORT_EXECUTION = 'EXECUTION_REPORT_EXECUTION'; 24 | export const EXECUTION_REPORT_CANCELED = 'EXECUTION_REPORT_CANCELED'; 25 | export const EXECUTION_REPORT_REJECTED = 'EXECUTION_REPORT_REJECTED'; 26 | 27 | export const ORDER_HISTORY = 'ORDER_HISTORY'; 28 | 29 | export const ORDER_SEND = 'ORDER_SEND'; 30 | export const ORDER_CANCEL = 'ORDER_CANCEL'; 31 | 32 | export const TRADE_HISTORY = 'TRADE_HISTORY'; 33 | 34 | export const TRADES = 'TRADES'; 35 | 36 | export const LOGIN = 'LOGIN'; 37 | export const LOGOUT = 'LOGOUT'; 38 | 39 | export const BALANCE = 'BALANCE'; 40 | export const POSITIONS = 'POSITIONS'; 41 | 42 | export const CUSTOMER_LIST = 'CUSTOMER_LIST'; 43 | export const CUSTOMER_REFRESH = 'CUSTOMER_REFRESH'; 44 | 45 | export const KYC_VERIFY = 'KYC_VERIFY'; 46 | export const KYC_REQUEST = 'KYC_REQUEST'; 47 | 48 | export const WITHDRAW_LIST = 'WITHDRAW_LIST'; 49 | export const WITHDRAW_CANCEL = 'WITHDRAW_CANCEL'; 50 | export const WITHDRAW_REFRESH = 'WITHDRAW_REFRESH'; 51 | export const WITHDRAW_PROCESS = 'WITHDRAW_PROCESS'; 52 | export const WITHDRAW_CONFIRM = 'WITHDRAW_CONFIRM'; 53 | export const WITHDRAW_COMMENT = 'WITHDRAW_COMMENT'; 54 | export const WITHDRAW_REQUEST = 'WITHDRAW_REQUEST'; 55 | 56 | export const DEPOSIT_LIST = 'DEPOSIT_LIST'; 57 | export const DEPOSIT_REFRESH = 'DEPOSIT_REFRESH'; 58 | export const DEPOSIT_PROCESS = 'DEPOSIT_PROCESS'; 59 | export const DEPOSIT_REQUEST = 'DEPOSIT_REQUEST'; 60 | export const DEPOSIT_METHODS = 'DEPOSIT_METHODS'; 61 | 62 | export const LEDGER_LIST = 'LEDGER_LIST'; 63 | -------------------------------------------------------------------------------- /src/constants/brokers.js: -------------------------------------------------------------------------------- 1 | export default { 2 | VBTC: 3, 3 | TESTNET: 5, 4 | URDUBIT: 8, 5 | CHILEBIT: 9, 6 | BITCAMBIO: 11, 7 | }; 8 | -------------------------------------------------------------------------------- /src/constants/common.js: -------------------------------------------------------------------------------- 1 | export default { 2 | prod: { 3 | ws: 'wss://ws.blinktrade.com/trade/', 4 | wsBitcambio: 'wss://bitcambio_api.blinktrade.com/trade/', 5 | rest: 'https://api.blinktrade.com/', 6 | restBitcambio: 'https://bitcambio_api.blinktrade.com/', 7 | }, 8 | testnet: { 9 | ws: 'wss://api_testnet.blinktrade.com/trade/', 10 | wsBitcambio: 'wss://api_testnet.blinktrade.com/trade/', 11 | rest: 'https://api_testnet.blinktrade.com/', 12 | restBitcambio: 'https://api_testnet.blinktrade.com/', 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /src/constants/markets.js: -------------------------------------------------------------------------------- 1 | export const BLINK_BTCBRL = 'BLINK:BTCBRL'; 2 | export const BLINK_BTCUSD = 'BLINK:BTCUSD'; 3 | export const BLINK_BTCCLP = 'BLINK:BTCCLP'; 4 | export const BLINK_BTCVND = 'BLINK:BTCVND'; 5 | export const UOL_USDBRT = 'UOL:USDBRT'; 6 | export const UOL_USDBRL = 'UOL:USDBRL'; 7 | -------------------------------------------------------------------------------- /src/constants/messages.js: -------------------------------------------------------------------------------- 1 | import * as reqs from './requestTypes'; 2 | import * as actions from './actionTypes'; 3 | import { msgToAction } from '../util/utils'; 4 | 5 | export const MsgActionReq = { 6 | 1: [actions.HEARTBEAT, reqs.TestReqID], 7 | BE: [actions.LOGIN, reqs.UserReqID], 8 | V: [actions.MD_FULL_REFRESH, reqs.MDReqID], 9 | x: [actions.SECURITY_LIST, reqs.SecurityReqID], 10 | e: [actions.SECURITY_STATUS_SUBSCRIBE, reqs.SecurityStatusReqID], 11 | D: [actions.ORDER_SEND, reqs.ClOrdID], 12 | F: [actions.ORDER_CANCEL, reqs.ClOrdID], 13 | U2: [actions.BALANCE, reqs.BalanceReqID], 14 | U6: [actions.WITHDRAW_REQUEST, reqs.WithdrawReqID], 15 | U4: [actions.ORDER_HISTORY, reqs.OrdersReqID], 16 | U18: [actions.DEPOSIT_REQUEST, reqs.DepositReqID], 17 | U20: [actions.DEPOSIT_METHODS, reqs.DepositMethodReqID], 18 | U24: [actions.WITHDRAW_CONFIRM, reqs.WithdrawReqID], 19 | U26: [actions.WITHDRAW_LIST, reqs.WithdrawListReqID], 20 | U28: [actions.BROKER_LIST, reqs.BrokerListReqID], 21 | U30: [actions.DEPOSIT_LIST, reqs.DepositListReqID], 22 | U32: [actions.TRADE_HISTORY, reqs.TradeHistoryReqID], 23 | U34: [actions.LEDGER_LIST, reqs.LedgerListReqID], 24 | U42: [actions.POSITIONS, reqs.PositionReqID], 25 | U70: [actions.WITHDRAW_CANCEL, reqs.WithdrawCancelReqID], 26 | B0: [actions.DEPOSIT_PROCESS, reqs.ProcessDepositReqID], 27 | B2: [actions.CUSTOMER_LIST, reqs.CustomerListReqID], 28 | B4: [actions.KYC_REQUEST, reqs.CustomerReqID], 29 | B6: [actions.WITHDRAW_PROCESS, reqs.ProcessWithdrawReqID], 30 | B8: [actions.KYC_VERIFY, reqs.VerifyCustomerReqID], 31 | }; 32 | 33 | export const MsgActionRes = { 34 | 0: [actions.HEARTBEAT, reqs.TestReqID], 35 | BF: [actions.LOGIN, reqs.UserReqID], 36 | W: [actions.MD_FULL_REFRESH, reqs.MDReqID], 37 | X: [actions.MD_INCREMENT, reqs.MDReqID], 38 | 8: [actions.EXECUTION_REPORT, reqs.ClOrdID], 39 | y: [actions.SECURITY_LIST, reqs.SecurityReqID], 40 | f: [actions.SECURITY_STATUS_SUBSCRIBE, reqs.SecurityStatusReqID], 41 | U3: [actions.BALANCE, reqs.BalanceReqID], 42 | U7: [actions.WITHDRAW_REQUEST, reqs.WithdrawReqID], 43 | U5: [actions.ORDER_HISTORY, reqs.OrdersReqID], 44 | U9: [actions.WITHDRAW_REFRESH, reqs.ClOrdID], 45 | U19: [actions.DEPOSIT_REQUEST, reqs.DepositReqID], 46 | U21: [actions.DEPOSIT_METHODS, reqs.DepositMethodReqID], 47 | U23: [actions.DEPOSIT_REFRESH, reqs.ClOrdID], 48 | U25: [actions.WITHDRAW_CONFIRM, reqs.WithdrawReqID], 49 | U27: [actions.WITHDRAW_LIST, reqs.WithdrawListReqID], 50 | U29: [actions.BROKER_LIST, reqs.BrokerListReqID], 51 | U31: [actions.DEPOSIT_LIST, reqs.DepositListReqID], 52 | U33: [actions.TRADE_HISTORY, reqs.TradeHistoryReqID], 53 | U35: [actions.LEDGER_LIST, reqs.LedgerListReqID], 54 | U43: [actions.POSITIONS, reqs.PositionReqID], 55 | U71: [actions.WITHDRAW_CANCEL, reqs.WithdrawCancelReqID], 56 | U79: [actions.WITHDRAW_COMMENT, reqs.WithdrawReqID], 57 | B1: [actions.DEPOSIT_PROCESS, reqs.ProcessDepositReqID], 58 | B3: [actions.CUSTOMER_LIST, reqs.CustomerListReqID], 59 | B5: [actions.KYC_REQUEST, reqs.CustomerReqID], 60 | B9: [actions.KYC_VERIFY, reqs.VerifyCustomerReqID], 61 | B7: [actions.WITHDRAW_PROCESS, reqs.ProcessWithdrawReqID], 62 | B11: [actions.CUSTOMER_REFRESH, ''], 63 | }; 64 | 65 | export const ActionMsgReq = msgToAction(MsgActionReq); 66 | export const ActionMsgRes = msgToAction(MsgActionRes); 67 | -------------------------------------------------------------------------------- /src/constants/requestTypes.js: -------------------------------------------------------------------------------- 1 | export const ReqID = 'ReqID'; 2 | export const TestReqID = 'TestReqID'; 3 | export const UserReqID = 'UserReqID'; 4 | export const SecurityReqID = 'SecurityReqID'; 5 | export const ResetPasswordReqID = 'ResetPasswordReqID'; 6 | export const DepositReqID = 'DepositReqID'; 7 | export const WithdrawReqID = 'WithdrawReqID'; 8 | export const BalanceReqID = 'BalanceReqID'; 9 | export const OrdersReqID = 'OrdersReqID'; 10 | export const EnableTwoFactorReqID = 'EnableTwoFactorReqID'; 11 | export const DepositMethodReqID = 'DepositMethodReqID'; 12 | export const WithdrawListReqID = 'WithdrawListReqID'; 13 | export const WithdrawCancelReqID = 'WithdrawCancelReqID'; 14 | export const BrokerListReqID = 'BrokerListReqID'; 15 | export const DepositListReqID = 'DepositListReqID'; 16 | export const TradeHistoryReqID = 'TradeHistoryReqID'; 17 | export const LedgerListReqID = 'LedgerListReqID'; 18 | export const TradersRankReqID = 'TradersRankReqID'; 19 | export const UpdateReqID = 'UpdateReqID'; 20 | export const PositionReqID = 'PositionReqID'; 21 | export const SecurityStatusReqID = 'SecurityStatusReqID'; 22 | export const APIKeyListReqID = 'APIKeyListReqID'; 23 | export const APIKeyCreateReqID = 'APIKeyCreateReqID'; 24 | export const APIKeyRevokeReqID = 'APIKeyRevokeReqID'; 25 | export const ProcessDepositReqID = 'ProcessDepositReqID'; 26 | export const CustomerListReqID = 'CustomerListReqID'; 27 | export const CustomerReqID = 'CustomerReqID'; 28 | export const ProcessWithdrawReqID = 'ProcessWithdrawReqID'; 29 | export const VerifyCustomerReqID = 'VerifyCustomerReqID'; 30 | export const MDReqID = 'MDReqID'; 31 | export const ClOrdID = 'ClOrdID'; 32 | -------------------------------------------------------------------------------- /src/constants/utils.js: -------------------------------------------------------------------------------- 1 | export const ORDER_BOOK_TRADE_NEW = 'TRADE_NEW'; 2 | export const ORDER_BOOK_NEW_ORDER = 'NEW_ORDER'; 3 | export const ORDER_BOOK_UPDATE_ORDER = 'UPDATE_ORDER'; 4 | export const ORDER_BOOK_DELETE_ORDER = 'DELETE_ORDER'; 5 | export const ORDER_BOOK_DELETE_ORDERS_THRU = 'DELETE_ORDERS_THRU'; 6 | 7 | export const EXECUTION_REPORT = 'EXECUTION_REPORT'; 8 | export const EXECUTION_REPORT_NEW = 'NEW'; 9 | export const EXECUTION_REPORT_PARTIAL = 'PARTIAL'; 10 | export const EXECUTION_REPORT_EXECUTION = 'EXECUTION'; 11 | export const EXECUTION_REPORT_CANCELED = 'CANCELED'; 12 | export const EXECUTION_REPORT_REJECTED = 'REJECTED'; 13 | 14 | /* eslint-disable quote-props */ 15 | export const EVENTS = { 16 | ORDERBOOK: { 17 | '0': ORDER_BOOK_NEW_ORDER, 18 | '1': ORDER_BOOK_UPDATE_ORDER, 19 | '2': ORDER_BOOK_DELETE_ORDER, 20 | '3': ORDER_BOOK_DELETE_ORDERS_THRU, 21 | }, 22 | TRADES: { 23 | '0': ORDER_BOOK_TRADE_NEW, 24 | }, 25 | EXECUTION_REPORT: { 26 | '0': EXECUTION_REPORT_NEW, 27 | '1': EXECUTION_REPORT_PARTIAL, 28 | '2': EXECUTION_REPORT_EXECUTION, 29 | '4': EXECUTION_REPORT_CANCELED, 30 | '8': EXECUTION_REPORT_REJECTED, 31 | }, 32 | }; 33 | 34 | export const ORDER_TYPE = { 35 | MARKET: '1', 36 | LIMIT: '2', 37 | STOP: '3', 38 | STOP_LIMIT: '4', 39 | }; 40 | 41 | export const ORDER_SIDE = { 42 | BUY: '1', 43 | SELL: '2', 44 | }; 45 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import Brokers from './constants/brokers'; 24 | import BlinkTradeWS from './ws'; 25 | import BlinkTradeRest from './rest'; 26 | 27 | export { 28 | Brokers, 29 | BlinkTradeWS, 30 | BlinkTradeRest, 31 | }; 32 | -------------------------------------------------------------------------------- /src/listener.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import { MsgActionReq, MsgActionRes } from './constants/messages'; 24 | 25 | import type { Message, MsgTypes, ResolveReject } from './types'; 26 | 27 | export const reqs: Map = new Map(); 28 | 29 | export function generateRequestId(): number { 30 | return parseInt(String(1e7 * Math.random()), 10); 31 | } 32 | 33 | function getKey(messages: MsgTypes, msg: Object): string { 34 | const key = messages[msg.MsgType][1]; 35 | const value = msg[key]; 36 | return key + ':' + value; 37 | } 38 | 39 | export function getRequest(msg: Message): ?ResolveReject { 40 | return reqs.get(getKey(MsgActionRes, msg)); 41 | } 42 | 43 | export function setRequest(msg: Message, promise: ResolveReject): void { 44 | reqs.set(getKey(MsgActionReq, msg), promise); 45 | } 46 | 47 | export function deleteRequest(msg: Message): void { 48 | reqs.delete(getKey(MsgActionRes, msg)); 49 | } 50 | -------------------------------------------------------------------------------- /src/rest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import nodeify from 'nodeify'; 24 | import RestTransport from './transports/rest'; 25 | import TradeBase from './trade'; 26 | 27 | import type { 28 | Message, 29 | BlinkTradeRestParams, 30 | BlinkTradeRestTransport, 31 | } from './types'; 32 | 33 | class BlinkTradeRest extends TradeBase { 34 | transport: BlinkTradeRestTransport; 35 | 36 | constructor(params?: BlinkTradeRestParams = {}) { 37 | super(params); 38 | this.transport = params.transport || new RestTransport(params); 39 | } 40 | 41 | send(msg: Message): Promise { 42 | return this.transport.fetchTrade(msg); 43 | } 44 | 45 | fetchPublic(path: string): Promise { 46 | return this.transport.fetchPublic(path); 47 | } 48 | 49 | ticker(callback?: Function): Promise { 50 | return nodeify.extend(this.fetchPublic('ticker')).nodeify(callback); 51 | } 52 | 53 | trades({ limit = 100, since = 0 }: { 54 | limit?: number, 55 | since?: number, 56 | } = {}, callback?: Function): Promise { 57 | return nodeify.extend(this.fetchPublic(`trades?limit=${limit}&since=${since}`)).nodeify(callback); 58 | } 59 | 60 | orderbook(callback?: Function): Promise { 61 | return nodeify.extend(this.fetchPublic('orderbook')).nodeify(callback); 62 | } 63 | } 64 | 65 | export default BlinkTradeRest; 66 | -------------------------------------------------------------------------------- /src/trade.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import nodeify from 'nodeify'; 24 | import { ActionMsgReq } from './constants/messages'; 25 | import { formatColumns, formatBrokerList } from './util/utils'; 26 | import { generateRequestId } from './listener'; 27 | import { ORDER_TYPE, ORDER_SIDE } from './constants/utils'; 28 | 29 | import type { 30 | Message, 31 | OrderSide, 32 | OrderType, 33 | OrderFilter, 34 | StatusListType, 35 | BlinkTradeEnv, 36 | BlinkTradeParams, 37 | BlinkTradeLevel, 38 | } from './types'; 39 | 40 | class TradeBase { 41 | env: BlinkTradeEnv; 42 | 43 | level: BlinkTradeLevel; 44 | 45 | brokerId: number; 46 | 47 | +send: (msg: Message) => Promise; 48 | 49 | constructor(params?: BlinkTradeParams = {}) { 50 | this.level = params.level === undefined ? 2 : params.level; 51 | 52 | this.brokerId = params.brokerId || 4; 53 | } 54 | 55 | changeBrokerId(brokerId: number) { 56 | this.brokerId = brokerId; 57 | } 58 | 59 | balance(clientId?: string, callback?: Function): Promise { 60 | const msg: Message = { 61 | MsgType: ActionMsgReq.BALANCE, 62 | BalanceReqID: generateRequestId(), 63 | }; 64 | 65 | if (clientId) { 66 | msg.ClientID = clientId; 67 | } 68 | 69 | return nodeify.extend(this.send(msg)).nodeify(callback); 70 | } 71 | 72 | myOrders({ 73 | page: Page = 0, 74 | pageSize: PageSize = 40, 75 | filter, 76 | }: { 77 | page?: number, 78 | pageSize?: number, 79 | filter?: OrderFilter, 80 | } = {}, callback?: Function): Promise { 81 | const msg: Message = { 82 | MsgType: ActionMsgReq.ORDER_HISTORY, 83 | OrdersReqID: generateRequestId(), 84 | Page, 85 | PageSize, 86 | }; 87 | 88 | if (filter && filter !== 'all') { 89 | msg.Filter = filter === 'open' ? ['has_leaves_qty eq 1'] 90 | : filter === 'filled' ? ['has_cum_qty eq 1'] 91 | : filter === 'cancelled' ? ['has_cxl_qty eq 1'] 92 | : filter; 93 | } 94 | 95 | const format = formatColumns('OrdListGrp', this.level); 96 | 97 | return nodeify.extend(this.send(msg).then(format)).nodeify(callback); 98 | } 99 | 100 | sendOrder({ type, side, amount, price, stopPrice, symbol, postOnly, clientId }: { 101 | side: OrderSide, 102 | type?: OrderType, 103 | price?: number, 104 | stopPrice?: number, 105 | amount: number, 106 | symbol: string, 107 | clientId?: string, 108 | postOnly?: boolean, 109 | }, callback?: Function): Promise { 110 | const msg: Message = { 111 | MsgType: ActionMsgReq.ORDER_SEND, 112 | ClOrdID: clientId || generateRequestId().toString(), 113 | Side: ORDER_SIDE[side] || side, 114 | OrdType: ORDER_TYPE[type] || ORDER_TYPE.LIMIT, 115 | Symbol: symbol, 116 | OrderQty: amount, 117 | BrokerID: this.brokerId, 118 | }; 119 | 120 | if (price) { 121 | msg.Price = price; 122 | } 123 | if (stopPrice) { 124 | msg.StopPx = stopPrice; 125 | } 126 | if (postOnly) { 127 | msg.ExecInst = '6'; 128 | } 129 | 130 | return nodeify.extend(this.send(msg)).nodeify(callback); 131 | } 132 | 133 | cancelOrder(param?: number | { 134 | orderId?: number, 135 | clientId?: string, 136 | side?: OrderSide, 137 | } = {}, callback?: Function): Promise { 138 | const orderId = param.orderId ? param.orderId : param; 139 | const msg: Message = { 140 | MsgType: ActionMsgReq.ORDER_CANCEL, 141 | }; 142 | 143 | if (param.clientId) { 144 | msg.ClOrdID = param.clientId; 145 | } 146 | 147 | if (param.orderId) { 148 | msg.OrderID = orderId; 149 | } 150 | 151 | if (param.side) { 152 | msg.Side = ORDER_SIDE[param.side] || param.side; 153 | } 154 | 155 | return nodeify.extend(this.send(msg)).nodeify(callback); 156 | } 157 | 158 | /** 159 | * status: 1-Pending, 2-In Progress, 4-Completed, 8-Cancelled 160 | */ 161 | requestWithdrawList({ 162 | filter, 163 | clientId, 164 | page: Page = 0, 165 | pageSize: PageSize = 20, 166 | status: StatusList = ['1', '2', '4', '8'], 167 | }: { 168 | page?: number, 169 | pageSize?: number, 170 | clientId?: string, 171 | filter?: Array, 172 | status?: Array, 173 | } = {}, callback?: Function): Promise { 174 | const msg: Message = { 175 | MsgType: ActionMsgReq.WITHDRAW_LIST, 176 | WithdrawListReqID: generateRequestId(), 177 | Page, 178 | PageSize, 179 | StatusList, 180 | }; 181 | 182 | if (filter && filter.length) { 183 | msg.Filter = filter; 184 | } 185 | 186 | if (clientId) { 187 | msg.ClientID = clientId; 188 | } 189 | 190 | const format = formatColumns('WithdrawListGrp', this.level); 191 | 192 | return nodeify.extend(this.send(msg).then(format)).nodeify(callback); 193 | } 194 | 195 | requestWithdraw({ amount, data, currency = 'BTC', method = 'bitcoin' }: { 196 | data: Object, 197 | amount: number, 198 | method?: string, 199 | currency?: string, 200 | }, callback?: Function): Promise { 201 | const reqId = generateRequestId(); 202 | const msg: Message = { 203 | MsgType: ActionMsgReq.WITHDRAW_REQUEST, 204 | WithdrawReqID: reqId, 205 | ClOrdID: reqId, 206 | Method: method, 207 | Amount: amount, 208 | Currency: currency, 209 | Data: data, 210 | }; 211 | 212 | return nodeify.extend(this.send(msg)).nodeify(callback); 213 | } 214 | 215 | confirmWithdraw({ withdrawId: WithdrawID, confirmationToken, secondFactor }: { 216 | withdrawId: string, 217 | confirmationToken?: string, 218 | secondFactor?: string, 219 | }, callback?: Function): Promise { 220 | const msg: Message = { 221 | MsgType: ActionMsgReq.WITHDRAW_CONFIRM, 222 | WithdrawReqID: generateRequestId(), 223 | WithdrawID, 224 | }; 225 | 226 | if (confirmationToken) { 227 | msg.ConfirmationToken = confirmationToken; 228 | } 229 | 230 | if (secondFactor) { 231 | msg.SecondFactor = secondFactor; 232 | } 233 | 234 | return nodeify.extend(this.send(msg)).nodeify(callback); 235 | } 236 | 237 | cancelWithdraw(withdrawId: string, callback?: Function): Promise { 238 | const reqId = generateRequestId(); 239 | const msg: Message = { 240 | MsgType: ActionMsgReq.WITHDRAW_CANCEL, 241 | WithdrawCancelReqID: reqId, 242 | ClOrdID: reqId, 243 | WithdrawID: withdrawId, 244 | }; 245 | 246 | return nodeify.extend(this.send(msg)).nodeify(callback); 247 | } 248 | 249 | requestDepositList({ 250 | page: Page = 0, 251 | pageSize: PageSize = 20, 252 | status: StatusList = ['1', '2', '4', '8'], 253 | filter, 254 | clientId, 255 | }: { 256 | page?: number, 257 | pageSize?: number, 258 | status?: Array, 259 | filter?: Array, 260 | clientId?: string, 261 | } = {}, callback?: Function): Promise { 262 | const msg: Message = { 263 | MsgType: ActionMsgReq.DEPOSIT_LIST, 264 | DepositListReqID: generateRequestId(), 265 | Page, 266 | PageSize, 267 | StatusList, 268 | }; 269 | 270 | if (filter && filter.length) { 271 | msg.Filter = filter; 272 | } 273 | 274 | if (clientId) { 275 | msg.ClientID = clientId; 276 | } 277 | 278 | const format = formatColumns('DepositListGrp', this.level); 279 | 280 | return nodeify.extend(this.send(msg).then(format)).nodeify(callback); 281 | } 282 | 283 | requestDeposit({ currency = 'BTC', value, depositMethodId }: { 284 | value?: number, 285 | currency?: string, 286 | depositMethodId?: number, 287 | } = {}, callback?: Function): Promise { 288 | const reqId = generateRequestId(); 289 | const msg: Message = { 290 | MsgType: ActionMsgReq.DEPOSIT_REQUEST, 291 | DepositReqID: reqId, 292 | ClOrdID: reqId, 293 | Currency: currency, 294 | BrokerID: this.brokerId, 295 | }; 296 | 297 | if (currency !== 'BTC') { 298 | msg.DepositMethodID = depositMethodId; 299 | msg.Value = value; 300 | } 301 | 302 | return nodeify.extend(this.send(msg)).nodeify(callback); 303 | } 304 | 305 | requestDepositMethods(callback?: Function): Promise { 306 | const msg: Message = { 307 | MsgType: ActionMsgReq.DEPOSIT_METHODS, 308 | DepositMethodReqID: generateRequestId(), 309 | BrokerID: this.brokerId, 310 | }; 311 | 312 | return nodeify.extend(this.send(msg)).nodeify(callback); 313 | } 314 | 315 | requestBrokerList(callback?: Function): Promise { 316 | const msg: Message = { 317 | MsgType: ActionMsgReq.BROKER_LIST, 318 | BrokerListReqID: generateRequestId(), 319 | Page: 0, 320 | PageSize: 20, 321 | StatusList: ['1'], 322 | }; 323 | 324 | const format = formatBrokerList(this.level); 325 | 326 | return nodeify.extend(this.send(msg).then(format)).nodeify(callback); 327 | } 328 | 329 | requestLedger({ 330 | page: Page = 0, 331 | pageSize: PageSize = 20, 332 | brokerId, 333 | clientId, 334 | currency, 335 | }: { 336 | page?: number, 337 | pageSize?: number, 338 | currency?: string, 339 | brokerId?: number, 340 | clientId?: string, 341 | } = {}, callback?: Function) { 342 | const msg: Message = { 343 | MsgType: ActionMsgReq.LEDGER_LIST, 344 | LedgerListReqID: generateRequestId(), 345 | BrokerID: this.brokerId, 346 | Page, 347 | PageSize, 348 | }; 349 | 350 | if (brokerId) { 351 | msg.BrokerID = brokerId; 352 | } 353 | if (currency) { 354 | msg.Currency = currency; 355 | } 356 | if (clientId) { 357 | msg.ClientID = clientId; 358 | } 359 | 360 | const format = formatColumns('LedgerListGrp', this.level); 361 | 362 | return nodeify.extend(this.send(msg).then(format)).nodeify(callback); 363 | } 364 | } 365 | 366 | export default TradeBase; 367 | -------------------------------------------------------------------------------- /src/transports/__mocks__/messages.js: -------------------------------------------------------------------------------- 1 | import { ActionMsgReq } from '../../constants/messages'; 2 | 3 | const { 4 | LOGIN, 5 | BALANCE, 6 | HEARTBEAT, 7 | ORDER_SEND, 8 | MD_FULL_REFRESH, 9 | DEPOSIT_REQUEST, 10 | WITHDRAW_REQUEST, 11 | SECURITY_STATUS_SUBSCRIBE, 12 | } = ActionMsgReq; 13 | 14 | export default { 15 | [HEARTBEAT]: (msg) => { 16 | global.Date.now = () => msg.SendTime; 17 | return { 18 | MsgType: '0', 19 | TestReqID: msg.TestReqID, 20 | ServerTimestamp: 1530850321, 21 | SendTime: msg.SendTime - 1000, 22 | }; 23 | }, 24 | [LOGIN]: (msg) => { 25 | if (msg.UserReqTyp === '2') { 26 | // Return logout 27 | return { 28 | MsgType: 'BF', 29 | Username: 'user', 30 | UserID: 90800078, 31 | UserReqID: 6821573, 32 | UserStatus: 2, 33 | }; 34 | } 35 | 36 | if (msg.Username !== 'user' || msg.Password !== 'abc12345') { 37 | // Return invalid authentication 38 | return { 39 | MsgType: 'BF', 40 | Username: 'user', 41 | NeedSecondFactor: false, 42 | UserStatusText: 'MSG_LOGIN_ERROR_INVALID_USERNAME_OR_PASSWORD', 43 | SecondFactorType: null, 44 | UserReqID: 823330, 45 | UserStatus: 3, 46 | }; 47 | } 48 | 49 | return { 50 | MsgType: 'BF', 51 | UserStatus: 1, 52 | Verified: 5, 53 | UserID: 90800078, 54 | TwoFactorEnabled: false, 55 | SignupReferrer: null, 56 | EmailLang: 'pt_BR', 57 | IsBrokerUser: false, 58 | Username: 'user', 59 | IsMSB: false, 60 | WithdrawFixedFee: null, 61 | HasLineOfCredit: false, 62 | IsBroker: false, 63 | Broker: {}, 64 | Profile: {}, 65 | TakerTransactionFeeSell: null, 66 | ConfirmationOrder: false, 67 | TakerTransactionFeeBuy: null, 68 | UserReqID: 153624, 69 | IsMarketMaker: false, 70 | DepositPercentFee: null, 71 | DepositFixedFee: null, 72 | WithdrawPercentFee: null, 73 | PermissionList: { 74 | '*': [], 75 | }, 76 | TransactionFeeBuy: null, 77 | TransactionFeeSell: null, 78 | EmailTwoFactorEnabled: false, 79 | LoginReferrer: null, 80 | BrokerID: 4, 81 | IsSystem: false, 82 | }; 83 | }, 84 | [BALANCE]: () => ({ 85 | 4: { 86 | BTC: 175010738, 87 | BRL: 76193959964295, 88 | BTC_locked: 0, 89 | BRL_locked: 1773864920000, 90 | }, 91 | MsgType: 'U3', 92 | ClientID: 90800078, 93 | BalanceReqID: 19569, 94 | }), 95 | [SECURITY_STATUS_SUBSCRIBE]: (msg) => ({ 96 | SellVolume: 606930000, 97 | LowPx: 1643700000000, 98 | LastPx: 1643700000000, 99 | MsgType: 'f', 100 | BestAsk: 11370000000000, 101 | HighPx: 1654000000000, 102 | BuyVolume: 10033395090000, 103 | BestBid: 1643700000000, 104 | Symbol: 'BTCBRL', 105 | SecurityStatusReqID: msg.SecurityStatusReqID, 106 | Market: 'BLINK', 107 | }), 108 | [MD_FULL_REFRESH]: (msg) => ({ 109 | MDReqID: msg.MDReqID, 110 | Symbol: 'BTCBRL', 111 | MsgType: 'W', 112 | MDFullGrp: [{ 113 | MDEntryPositionNo: 1, 114 | MDEntrySize: 74900000, 115 | MDEntryPx: 1642400000000, 116 | MDEntryID: 1459030499584, 117 | MDEntryTime: '07:01:02', 118 | MDEntryDate: '2018-03-26', 119 | UserID: 90804823, 120 | OrderID: 1459030499584, 121 | MDEntryType: '0', 122 | Broker: 'bitcambio', 123 | }, { 124 | MDEntryPositionNo: 2, 125 | MDEntrySize: 200000000, 126 | MDEntryPx: 1637400000000, 127 | MDEntryID: 1459030499586, 128 | MDEntryTime: '07:01:12', 129 | MDEntryDate: '2018-03-26', 130 | UserID: 90804823, 131 | OrderID: 1459030499586, 132 | MDEntryType: '0', 133 | Broker: 'bitcambio', 134 | }, { 135 | MDEntryPositionNo: 1, 136 | MDEntrySize: 68008, 137 | MDEntryPx: 2832642000000, 138 | MDEntryID: 1459030505672, 139 | MDEntryTime: '22:15:21', 140 | MDEntryDate: '2018-07-17', 141 | UserID: 90800025, 142 | OrderID: 1459030505672, 143 | MDEntryType: '1', 144 | Broker: 'bitcambio', 145 | }, { 146 | MDEntryPositionNo: 2, 147 | MDEntrySize: 206000, 148 | MDEntryPx: 11370000000000, 149 | MDEntryID: 1459030449304, 150 | MDEntryTime: '23:39:12', 151 | MDEntryDate: '2017-06-19', 152 | UserID: 90800027, 153 | OrderID: 1459030449304, 154 | MDEntryType: '1', 155 | Broker: 'foxbit', 156 | }], 157 | MarketDepth: 1000, 158 | }), 159 | [ORDER_SEND]: (msg) => ({ 160 | OrderID: 1459030505940, 161 | ExecID: 9164, 162 | ExecType: '0', 163 | OrdStatus: '0', 164 | CumQty: 0, 165 | Symbol: 'BTCBRL', 166 | OrderQty: 99568462, 167 | LastShares: 0, 168 | LastPx: 0, 169 | Price: 1637400000000, 170 | TimeInForce: '1', 171 | LeavesQty: 99568462, 172 | MsgType: '8', 173 | ExecSide: '1', 174 | OrdType: '2', 175 | CxlQty: 0, 176 | Side: '1', 177 | ClOrdID: msg.ClOrdID, 178 | AvgPx: 0, 179 | }), 180 | [DEPOSIT_REQUEST]: (msg) => ({ 181 | MsgType: 'U19', 182 | DepositReqID: msg.DepositReqID, 183 | DepositMethodName: 'ted_doc', 184 | UserID: 90800078, 185 | ControlNumber: 404000014, 186 | State: 'UNCONFIRMED', 187 | Type: 'DTP', 188 | PercentFee: 0.0, 189 | Username: 'cesaraugusto', 190 | CreditProvided: 0, 191 | DepositID: '55aeeb2a8146423088f35f7846bc64e6', 192 | Reason: null, 193 | AccountID: 90800078, 194 | Data: {}, 195 | ClOrdID: msg.ClOrdID, 196 | Status: '0', 197 | Created: '2018-07-18 00:42:03', 198 | DepositMethodID: 404, 199 | Value: 50000000000, 200 | BrokerID: 4, 201 | PaidValue: 0, 202 | Currency: 'BRL', 203 | ReasonID: null, 204 | FixedFee: 0, 205 | }), 206 | [WITHDRAW_REQUEST]: (msg) => ({ 207 | MsgType: 'U7', 208 | Username: 'cesaraugusto', 209 | Status: '1', 210 | SecondFactorType: '', 211 | Created: '2018-07-18 01:06:47', 212 | PaidAmount: 10000000000, 213 | UserID: 90800078, 214 | Reason: null, 215 | Currency: 'BRL', 216 | Amount: msg.Amount, 217 | ReasonID: null, 218 | BrokerID: 4, 219 | ClOrdID: msg.ClOrdID, 220 | WithdrawID: 1532, 221 | WithdrawReqID: msg.WithdrawReqID, 222 | Data: { 223 | Memo: 'Memo', 224 | Instant: 'NO', 225 | email: 'user@blinktrade.com', 226 | Fees: 'R$ 0.00', 227 | }, 228 | Method: 'Paypal', 229 | FixedFee: 0, 230 | PercentFee: 0.0, 231 | }), 232 | }; 233 | -------------------------------------------------------------------------------- /src/transports/__mocks__/websocket.js: -------------------------------------------------------------------------------- 1 | import nodeify from 'nodeify'; 2 | import EventEmitter from 'eventemitter2'; 3 | import messages from './messages'; 4 | 5 | export default jest.fn().mockImplementation(() => { 6 | return { 7 | eventEmitter: new EventEmitter({ wildcard: true, delimiter: ':' }), 8 | 9 | connect(callback) { 10 | return nodeify.extend(new Promise((resolve) => { 11 | setTimeout(() => { 12 | this.eventEmitter.emit('OPEN', {}); 13 | return resolve({ connected: true }); 14 | }); 15 | })).nodeify(callback); 16 | }, 17 | 18 | sendMessageAsPromise(req) { 19 | this.req = req; 20 | return new Promise((resolve) => { 21 | const type = req.MsgType; 22 | const mock = messages[type]; 23 | const res = mock ? mock(req) : {}; 24 | this.eventEmitter.emit(res.MsgType, res); 25 | return resolve(res); 26 | }); 27 | }, 28 | 29 | emitterPromise(promise, callback) { 30 | promise.on = (event, listener) => { 31 | this.eventEmitter.on(event, listener); 32 | return promise; 33 | }; 34 | 35 | return nodeify.extend(promise).nodeify(callback); 36 | }, 37 | }; 38 | }); 39 | -------------------------------------------------------------------------------- /src/transports/rest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import sha256 from 'js-sha256'; 24 | import invariant from 'invariant'; 25 | import fetchPonyfill from 'fetch-ponyfill'; 26 | 27 | import BROKERS from '../constants/brokers'; 28 | import Transport from './transport'; 29 | 30 | import type { 31 | Message, 32 | BlinkTradeRestParams, 33 | BlinkTradeCurrencies, 34 | } from '../types'; 35 | 36 | const { fetch } = fetchPonyfill({ Promise }); 37 | 38 | class RestTransport extends Transport { 39 | /** 40 | * APIKey 41 | */ 42 | key: ?string; 43 | 44 | /** 45 | * APISecret 46 | */ 47 | secret: ?string; 48 | 49 | /** 50 | * Exchanges currencies available. 51 | */ 52 | currency: BlinkTradeCurrencies; 53 | 54 | constructor(params?: BlinkTradeRestParams = {}) { 55 | super(params, params.brokerId === BROKERS.BITCAMBIO ? 'restBitcambio' : 'rest'); 56 | 57 | this.key = params.key; 58 | this.secret = params.secret; 59 | this.currency = params.currency || 'BRL'; 60 | } 61 | 62 | headers(method: string, body: Object): Object { 63 | const timeStamp = Date.now().toString(); 64 | const Signature = sha256.hmac.create(this.secret).update(timeStamp).hex(); 65 | 66 | return { 67 | method, 68 | headers: { 69 | 'Content-Type': 'application/json', 70 | Nonce: timeStamp, 71 | APIKey: this.key, 72 | Signature, 73 | }, 74 | body: JSON.stringify(body), 75 | }; 76 | } 77 | 78 | fetch(api: string, headers?: Object = {}): Promise { 79 | return fetch(this.endpoint + api, headers) 80 | .then(response => response.json()); 81 | } 82 | 83 | fetchPublic(api: string): Promise { 84 | return this.fetch(`api/v1/${this.currency}/${api}`); 85 | } 86 | 87 | fetchTrade(msg: Message): Promise { 88 | invariant(this.key && this.secret, 'Key or Secret not provided'); 89 | const headers = this.headers('POST', msg); 90 | return this.fetch('tapi/v1/message', headers) 91 | .then(response => (response.Status === 500 ? Promise.reject(response) : response.Responses)) 92 | .then(response => (response.length === 1 ? response[0] : response)); 93 | } 94 | } 95 | 96 | export default RestTransport; 97 | -------------------------------------------------------------------------------- /src/transports/transport.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import common from '../constants/common'; 24 | 25 | import type { 26 | BlinkTradeEnv, 27 | BlinkTradeParams, 28 | } from '../types'; 29 | 30 | export const IS_NODE = typeof window === 'undefined'; 31 | export const IS_BROWSER = typeof document !== 'undefined'; 32 | 33 | class Transport { 34 | /* 35 | * url endpoint. 36 | */ 37 | endpoint: string; 38 | 39 | constructor(params: BlinkTradeParams = {}, env: BlinkTradeEnv) { 40 | /* eslint-disable indent */ 41 | this.endpoint = 42 | params.url ? params.url 43 | : params.prod ? common.prod[env] 44 | : common.testnet[env]; 45 | /* eslint-enable indent */ 46 | } 47 | } 48 | 49 | export default Transport; 50 | -------------------------------------------------------------------------------- /src/transports/websocket.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import WS from 'ws'; 24 | import nodeify from 'nodeify'; 25 | import EventEmitter from 'eventemitter2'; 26 | import { getMac } from '../util/macaddress'; 27 | import { getFingerPrint } from '../util/fingerPrint'; 28 | import { getStun, closeStun } from '../util/stun'; 29 | import { MsgActionRes } from '../constants/messages'; 30 | 31 | import BROKERS from '../constants/brokers'; 32 | 33 | import Transport, { IS_NODE, IS_BROWSER } from './transport'; 34 | import type { 35 | Stun, 36 | Message, 37 | ResolveReject, 38 | PromiseEmitter, 39 | BlinkTradeWSParams, 40 | } from '../types'; 41 | 42 | import { 43 | getRequest, 44 | setRequest, 45 | deleteRequest, 46 | } from '../listener'; 47 | 48 | const RECONNECT_INTERVAL = 5000; 49 | 50 | class WebSocketTransport extends Transport { 51 | /* 52 | * WebSocket Instance 53 | */ 54 | socket: WebSocket; 55 | 56 | /* 57 | * FingerPrint 58 | */ 59 | fingerPrint: string; 60 | 61 | /* 62 | * Stun object 63 | */ 64 | stun: Stun; 65 | 66 | connection: ResolveReject; 67 | lastPromise: ResolveReject; 68 | 69 | lastMessageSent: Message; 70 | 71 | /* 72 | * Event emitter to dispatch websocket updates 73 | */ 74 | eventEmitter: EventEmitter; 75 | 76 | headers: ?Object; 77 | 78 | autoReconnect: boolean; 79 | 80 | reconnectInterval: number; 81 | 82 | constructor(params?: BlinkTradeWSParams = {}) { 83 | super(params, params.brokerId === BROKERS.BITCAMBIO ? 'wsBitcambio' : 'ws'); 84 | 85 | this.stun = { local: null, public: [] }; 86 | 87 | this.getFingerPrint(params.fingerPrint); 88 | this.headers = params.headers; 89 | this.autoReconnect = params.reconnect || false; 90 | this.reconnectInterval = params.reconnectInterval || RECONNECT_INTERVAL; 91 | 92 | this.eventEmitter = new EventEmitter({ wildcard: true, delimiter: ':' }); 93 | } 94 | 95 | connect(callback?: Function): Promise { 96 | return nodeify.extend(new Promise((resolve, reject) => { 97 | this.connection = { resolve, reject }; 98 | 99 | const WebSocket = IS_NODE ? WS : window.WebSocket; 100 | 101 | this.getStun(); 102 | 103 | this.socket = new WebSocket(this.endpoint, [], this.headers); 104 | this.socket.onopen = this.onOpen.bind(this); 105 | this.socket.onclose = this.onClose.bind(this); 106 | this.socket.onerror = this.onError.bind(this); 107 | this.socket.onmessage = this.onMessage.bind(this); 108 | })).nodeify(callback); 109 | } 110 | 111 | disconnect(): void { 112 | this.socket.close(); 113 | this.closeStun(); 114 | } 115 | 116 | onOpen(e: Event): void { 117 | this.eventEmitter.emit('OPEN', e); 118 | this.connection.resolve({ connected: true }); 119 | } 120 | 121 | onClose(e: Event): void { 122 | this.eventEmitter.emit('CLOSE', e, this.lastMessageSent); 123 | this.closeStun(); 124 | this.reconnect(); 125 | } 126 | 127 | onError(error: Event): void { 128 | this.eventEmitter.emit('ERROR', error, this.lastMessageSent); 129 | } 130 | 131 | reconnect() { 132 | if (this.autoReconnect) { 133 | setTimeout(() => this.connect(), this.reconnectInterval); 134 | } 135 | } 136 | 137 | sendMessage(msg: Message): void { 138 | if (this.socket.readyState === 1) { 139 | const data = msg; 140 | 141 | data.STUNTIP = this.stun; 142 | data.FingerPrint = this.fingerPrint; 143 | 144 | this.lastMessageSent = data; 145 | this.eventEmitter.emit('send', data); 146 | this.socket.send(JSON.stringify(data)); 147 | } 148 | } 149 | 150 | sendMessageAsPromise(msg: Message): Promise { 151 | return new Promise((resolve, reject) => { 152 | this.lastPromise = { resolve, reject }; 153 | setRequest(msg, { resolve, reject }); 154 | this.sendMessage(msg); 155 | }); 156 | } 157 | 158 | onMessage(msg: Object): void { 159 | const data = JSON.parse(msg.data); 160 | 161 | this.eventEmitter.emit('receive', data); 162 | 163 | if (!MsgActionRes[data.MsgType]) { 164 | if (data.MsgType === 'ERROR') { 165 | this.eventEmitter.emit('ERROR', data, this.lastMessageSent); 166 | } 167 | 168 | return; 169 | } 170 | 171 | this.dispatchPromise(data); 172 | this.dispatchEventEmitters(data); 173 | } 174 | 175 | dispatchPromise(data: Object): any { 176 | const request = getRequest(data); 177 | if (request && request.resolve) { 178 | deleteRequest(data); 179 | return request.resolve(data); 180 | } 181 | } 182 | 183 | dispatchEventEmitters(data: Object): any { 184 | const type = data.MsgType; 185 | const reqId = MsgActionRes[type][1]; 186 | 187 | this.eventEmitter.emit(type, data); 188 | if (data[reqId]) { 189 | this.eventEmitter.emit(type + ':' + data[reqId], data); 190 | } 191 | } 192 | 193 | getFingerPrint(customFingerprint?: string): void { 194 | if (IS_NODE) { 195 | return getMac(macAddress => { 196 | this.fingerPrint = macAddress; 197 | }); 198 | } else if (IS_BROWSER) { 199 | this.fingerPrint = getFingerPrint(); 200 | } else if (customFingerprint) { 201 | this.fingerPrint = customFingerprint; 202 | } else { 203 | throw new Error('FingerPrint not provided'); 204 | } 205 | } 206 | 207 | getStun(): void { 208 | if (IS_NODE) { 209 | getStun(data => { 210 | this.stun = data; 211 | }); 212 | } 213 | } 214 | 215 | closeStun(): void { 216 | if (IS_NODE) { 217 | closeStun(); 218 | } 219 | } 220 | 221 | /* eslint-disable no-param-reassign */ 222 | emitterPromise(promise: Object, callback?: Function): PromiseEmitter { 223 | promise.on = (event: string, listener: Function) => { 224 | this.eventEmitter.on(event, listener); 225 | return promise; 226 | }; 227 | promise.onAny = (listener: Function) => { 228 | this.eventEmitter.onAny(listener); 229 | return promise; 230 | }; 231 | promise.offAny = (listener: Function) => { 232 | this.eventEmitter.offAny(listener); 233 | return promise; 234 | }; 235 | promise.once = (event: string, listener: Function) => { 236 | this.eventEmitter.once(event, listener); 237 | return promise; 238 | }; 239 | promise.many = (event: string, times: number, listener: Function) => { 240 | this.eventEmitter.many(event, times, listener); 241 | return promise; 242 | }; 243 | promise.removeListener = (event: string, listener: Function) => { 244 | this.eventEmitter.removeListener(event, listener); 245 | return promise; 246 | }; 247 | promise.removeAllListeners = (events: Array) => { 248 | this.eventEmitter.removeAllListeners(events); 249 | return promise; 250 | }; 251 | 252 | return nodeify.extend(promise).nodeify(callback); 253 | } 254 | /* eslint-enable no-param-reassign */ 255 | } 256 | 257 | export default WebSocketTransport; 258 | -------------------------------------------------------------------------------- /src/types.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | /* eslint-disable no-use-before-define */ 3 | import EventEmitter from 'eventemitter2'; 4 | 5 | export type BlinkTradeEnv = 6 | | 'ws' 7 | | 'rest' 8 | | 'wsBitcambio' 9 | | 'restBitcambio'; 10 | 11 | export type BlinkTradeLevel = 0 | 2; 12 | export type BlinkTradeCurrencies = | 'USD' | 'BRL' | 'CLP' | 'VND'; 13 | 14 | export type BlinkTradeRestTransport = { 15 | +fetchPublic: (string) => Promise, 16 | +fetchTrade: (msg: Message) => Promise, 17 | }; 18 | 19 | export type BlinkTradeWSTransport = { 20 | +connect: (callback?: Function) => Promise, 21 | +disconnect: () => void, 22 | +sendMessage: (msg: Message) => void, 23 | +sendMessageAsPromise: (msg: Message) => Promise, 24 | +emitterPromise?: (promise: any, callback?: Function) => PromiseEmitter, 25 | +eventEmitter: EventEmitter, 26 | }; 27 | 28 | export type BlinkTradeParams = { 29 | url?: string, 30 | prod?: boolean, 31 | brokerId?: number, 32 | transport?: any, 33 | level?: BlinkTradeLevel, 34 | }; 35 | 36 | export type BlinkTradeWSParams = { 37 | headers?: Object, 38 | fingerPrint?: string, 39 | reconnect?: boolean, 40 | reconnectInterval?: number, 41 | transport?: BlinkTradeWSTransport, 42 | } & BlinkTradeParams; 43 | 44 | export type BlinkTradeRestParams = { 45 | key?: string, 46 | secret?: string, 47 | currency?: BlinkTradeCurrencies, 48 | transport?: BlinkTradeRestTransport, 49 | } & BlinkTradeParams; 50 | 51 | export type Message = { 52 | MsgType: string, 53 | } & Object; 54 | 55 | export type MsgTypes = { 56 | [key: string]: [string, string] 57 | }; 58 | 59 | export type Stun = { 60 | local: ?Array, 61 | public: ?Array, 62 | }; 63 | 64 | export type OrderBookSync = { 65 | [symbol: string]: { 66 | bids: Array, 67 | asks: Array, 68 | } 69 | }; 70 | 71 | export type MarketDataParams = Array | { 72 | instruments: Array, 73 | columns?: Array, 74 | entryTypes?: Array<0 | 1 | 2>, 75 | marketDepth?: number, 76 | level?: BlinkTradeLevel, 77 | }; 78 | 79 | export type StatusListType = '1' | '2' | '4' | '8'; 80 | 81 | export type OrderSide = 'BUY' | 'SELL' | '1' | '2'; 82 | export type OrderType = 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_LIMIT'; 83 | export type OrderFilter = | Array | 'all' | 'open' | 'filled' | 'cancelled'; 84 | 85 | export type ResolveReject = { 86 | resolve: Function, 87 | reject: Function, 88 | }; 89 | 90 | export type PromiseEmitter = Promise & { 91 | on: (event: string, listener: Function) => PromiseEmitter, 92 | onAny: (listener: Function) => PromiseEmitter, 93 | offAny: (listener: Function) => PromiseEmitter, 94 | once: (event: string, listener: Function) => PromiseEmitter, 95 | many: (event: string, times: number, listener: Function) => PromiseEmitter, 96 | removeListener: (event: string, listener: Function) => PromiseEmitter, 97 | removeAllListeners: (events: Array) => PromiseEmitter, 98 | }; 99 | -------------------------------------------------------------------------------- /src/util/__mocks__/fingerPrint.js: -------------------------------------------------------------------------------- 1 | export function getFingerPrint() { 2 | return 'MOCK_FINGERPRINT'; 3 | } 4 | -------------------------------------------------------------------------------- /src/util/__mocks__/macaddress.js: -------------------------------------------------------------------------------- 1 | export function getMac(callback) { 2 | callback('MOCK_MACADDRESS'); 3 | } 4 | -------------------------------------------------------------------------------- /src/util/__mocks__/stun.js: -------------------------------------------------------------------------------- 1 | export function getStun(callback) { 2 | callback('MOCK_STUN'); 3 | } 4 | -------------------------------------------------------------------------------- /src/util/fingerPrint.js: -------------------------------------------------------------------------------- 1 | import sha256 from 'js-sha256'; 2 | import { encodeByteArray } from './hash32'; 3 | 4 | export function getFingerPrint() { 5 | const keys = []; 6 | keys.push(window.navigator.userAgent); 7 | keys.push(window.screen.colorDepth); 8 | keys.push(window.navigator.language); 9 | if (Array.isArray(window.navigator.languages)) { 10 | keys.push(window.navigator.languages.join('x')); 11 | } else { 12 | keys.push(typeof undefined); 13 | } 14 | const resolution = (window.screen.height > window.screen.width) 15 | ? [window.screen.height, window.screen.width] 16 | : [window.screen.width, window.screen.height]; 17 | keys.push(resolution.join('x')); 18 | keys.push(new Date().getTimezoneOffset()); 19 | keys.push(typeof window.sessionStorage !== 'undefined'); 20 | keys.push(typeof window.localStorage !== 'undefined'); 21 | keys.push(!!window.indexedDB); 22 | if (document.body) { 23 | keys.push(typeof window.document.body.addBehavior); 24 | } else { 25 | keys.push(typeof undefined); 26 | } 27 | keys.push(typeof window.openDatabase); 28 | keys.push(window.navigator.cpuClass); 29 | keys.push(window.navigator.platform); 30 | keys.push(window.navigator.doNotTrack); 31 | 32 | const pluginKeyList = []; 33 | Array.from(window.navigator.plugins).forEach((p) => { 34 | const mimeTypes = []; 35 | Object.values(p).forEach((mt) => { 36 | mimeTypes.push([mt.type, mt.suffixes].join('~')); 37 | }); 38 | pluginKeyList.push([p.name, p.description, mimeTypes.join(',')].join('::')); 39 | }); 40 | keys.push(pluginKeyList.join(';')); 41 | 42 | const canvasEl = document.createElement('canvas'); 43 | if (canvasEl.getContext && canvasEl.getContext('2d')) { 44 | const ctx = canvasEl.getContext('2d'); 45 | const txt = 'http://valve.github.io'; 46 | ctx.textBaseline = 'top'; 47 | ctx.font = "14px 'Arial'"; 48 | ctx.textBaseline = 'alphabetic'; 49 | ctx.fillStyle = '#f60'; 50 | ctx.fillRect(125, 1, 62, 20); 51 | ctx.fillStyle = '#069'; 52 | ctx.fillText(txt, 2, 15); 53 | ctx.fillStyle = 'rgba(102, 204, 0, 0.7)'; 54 | ctx.fillText(txt, 4, 17); 55 | keys.push(canvasEl.toDataURL()); 56 | } 57 | 58 | const digest = sha256.digest(keys.join('###')); 59 | 60 | let fingerPrint = parseInt(encodeByteArray(digest)); 61 | if (fingerPrint < 0) { 62 | fingerPrint *= -1; 63 | } 64 | return fingerPrint; 65 | } 66 | -------------------------------------------------------------------------------- /src/util/hash32.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-var */ 2 | /* eslint-disable no-bitwise */ 3 | /* eslint-disable no-param-reassign */ 4 | /* eslint-disable no-fallthrough */ 5 | /* eslint-disable no-underscore-dangle */ 6 | /* eslint-disable default-case */ 7 | /* eslint-disable prefer-destructuring */ 8 | /* 9 | * ByteArray enconding from google-closure-library 10 | */ 11 | 12 | const SEED32 = 314159265; 13 | const CONSTANT32 = -1640531527; 14 | 15 | /** 16 | * Performs an inplace mix of an object with the integer properties (a, b, c) 17 | * and returns the final value of c. 18 | * @param {Object} mix Object with properties, a, b, and c. 19 | * @return {number} The end c-value for the mixing. 20 | * @private 21 | */ 22 | const mix32_ = (mix) => { 23 | var a = mix.a; 24 | var b = mix.b; 25 | var c = mix.c; 26 | a -= b; 27 | a -= c; 28 | a ^= c >>> 13; 29 | b -= c; 30 | b -= a; 31 | b ^= a << 8; 32 | c -= a; 33 | c -= b; 34 | c ^= b >>> 13; 35 | a -= b; 36 | a -= c; 37 | a ^= c >>> 12; 38 | b -= c; 39 | b -= a; 40 | b ^= a << 16; 41 | c -= a; 42 | c -= b; 43 | c ^= b >>> 5; 44 | a -= b; 45 | a -= c; 46 | a ^= c >>> 3; 47 | b -= c; 48 | b -= a; 49 | b ^= a << 10; 50 | c -= a; 51 | c -= b; 52 | c ^= b >>> 15; 53 | mix.a = a; 54 | mix.b = b; 55 | mix.c = c; 56 | return c; 57 | }; 58 | 59 | /** 60 | * Converts an unsigned "byte" to signed, that is, convert a value in the range 61 | * (0, 2^8-1) to (-2^7, 2^7-1) in order to be compatible with Java's byte type. 62 | * @param {number} n Unsigned "byte" value. 63 | * @return {number} Signed "byte" value. 64 | * @private 65 | */ 66 | const toSigned_ = (n) => { 67 | return n > 127 ? n - 256 : n; 68 | }; 69 | 70 | const wordAt_ = (bytes, offset) => { 71 | var a = toSigned_(bytes[offset + 0]); 72 | var b = toSigned_(bytes[offset + 1]); 73 | var c = toSigned_(bytes[offset + 2]); 74 | var d = toSigned_(bytes[offset + 3]); 75 | return a + (b << 8) + (c << 16) + (d << 24); 76 | }; 77 | 78 | /** 79 | * Hashes a "byte" array to a 32-bit value using the supplied seed. 80 | */ 81 | export function encodeByteArray(bytes) { 82 | var offset = 0; 83 | var length = bytes.length; 84 | var seed = SEED32; 85 | 86 | var mix = { 87 | a: CONSTANT32, 88 | b: CONSTANT32, 89 | c: seed, 90 | }; 91 | 92 | var keylen; 93 | for (keylen = length; keylen >= 12; keylen -= 12, offset += 12) { 94 | mix.a += wordAt_(bytes, offset); 95 | mix.b += wordAt_(bytes, offset + 4); 96 | mix.c += wordAt_(bytes, offset + 8); 97 | mix32_(mix); 98 | } 99 | // Hash any remaining bytes 100 | mix.c += length; 101 | switch (keylen) { // deal with rest. Some cases fall through 102 | case 11: 103 | mix.c += (bytes[offset + 10]) << 24; 104 | case 10: 105 | mix.c += (bytes[offset + 9] & 0xff) << 16; 106 | case 9: 107 | mix.c += (bytes[offset + 8] & 0xff) << 8; 108 | // the first byte of c is reserved for the length 109 | case 8: 110 | mix.b += wordAt_(bytes, offset + 4); 111 | mix.a += wordAt_(bytes, offset); 112 | break; 113 | case 7: 114 | mix.b += (bytes[offset + 6] & 0xff) << 16; 115 | case 6: 116 | mix.b += (bytes[offset + 5] & 0xff) << 8; 117 | case 5: 118 | mix.b += (bytes[offset + 4] & 0xff); 119 | case 4: 120 | mix.a += wordAt_(bytes, offset); 121 | break; 122 | case 3: 123 | mix.a += (bytes[offset + 2] & 0xff) << 16; 124 | case 2: 125 | mix.a += (bytes[offset + 1] & 0xff) << 8; 126 | case 1: 127 | mix.a += (bytes[offset + 0] & 0xff); 128 | // case 0 : nothing left to add 129 | } 130 | return mix32_(mix); 131 | } 132 | -------------------------------------------------------------------------------- /src/util/macaddress.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | /* eslint-disable operator-assignment */ 24 | /* eslint-disable no-plusplus */ 25 | /* eslint-disable import/prefer-default-export */ 26 | import macaddress from 'macaddress-secure'; 27 | 28 | export function getMac(callback: Function): void { 29 | macaddress.all((err, all) => { 30 | const hashCode = (str) => { 31 | let hash = 0; 32 | if (str.length === 0) return hash; 33 | for (let i = 0; i < str.length; i++) { 34 | hash = ((hash << 5) - hash) + str.charCodeAt(i); 35 | hash = hash & hash; // Convert to 32bit integer 36 | } 37 | return hash; 38 | }; 39 | 40 | let macAddresses = ''; 41 | Object.keys(all).forEach(iface => { 42 | macAddresses += all[iface].mac; 43 | }); 44 | 45 | let fingerPrint = hashCode(macAddresses); 46 | if (fingerPrint < 0) { 47 | fingerPrint *= -1; 48 | } 49 | 50 | callback(fingerPrint); 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /src/util/stun.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | /* eslint-disable no-param-reassign */ 22 | /* eslint-disable no-plusplus */ 23 | /* eslint-disable import/prefer-default-export */ 24 | /* eslint-disable no-restricted-properties */ 25 | /* eslint-disable no-buffer-constructor */ 26 | 27 | import ip from 'ip'; 28 | import dgram from 'dgram'; 29 | 30 | const stunIp = { local: null, public: [] }; 31 | 32 | let socket; 33 | 34 | function addIPAddress(ipAddress) { 35 | if (ipAddress.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) { 36 | stunIp.local = ipAddress; 37 | } else if (stunIp.public.indexOf(ipAddress) === -1) { 38 | stunIp.public.push(ipAddress); 39 | } 40 | } 41 | 42 | export function closeStun() { 43 | if (socket._receiving) { 44 | socket.close(); 45 | } 46 | } 47 | 48 | export function getStun(callback) { 49 | socket = dgram.createSocket('udp4'); 50 | 51 | const STUN_HEADER_LENGTH = 20; 52 | const stunRequest = new Buffer(STUN_HEADER_LENGTH); 53 | 54 | const STUN_METHOD_REQUEST = 0x000; 55 | const STUN_BINDING_CLASS = 0x0001; 56 | const STUN_MAGIC_COOKIE = 0x2112A442; 57 | const STUN_TID_MAX = Math.pow(2, 32); 58 | 59 | const STUN_ATTR_MAPPED_ADDRESS = 0x0001; 60 | const STUN_ATTR_XOR_MAPPED_ADDRESS = 0x8020; 61 | const STUN_ATTR_XOR_MAPPED_ADDRESS_ALT = 0x0020; 62 | 63 | const stunTxId = (Math.random() * STUN_TID_MAX); 64 | 65 | const stunServers = [ 66 | [3478, 'stun.services.mozilla.com'], 67 | [19302, 'stun.l.google.com'], 68 | [3478, 'stun.stunprotocol.org'], 69 | [3478, 'stun.softjoys.com'], 70 | [3478, 'stun.samsungsmartcam.com'], 71 | [3478, 'stun.sonetel.com'], 72 | [3478, 'stun.tagan.ru'], 73 | [3478, 'stun.voipgain.com'], 74 | [3478, 'stunserver.org'], 75 | [3478, 'stun.advfn.com'], 76 | [3478, 'stun.annatel.net'], 77 | [3478, 'stun.freevoipdeal.com'], 78 | ]; 79 | 80 | stunRequest.writeUInt16BE(((STUN_BINDING_CLASS | STUN_METHOD_REQUEST) & 0x3fff), 0); 81 | stunRequest.writeUInt16BE(0, 2); 82 | stunRequest.writeUInt32BE(STUN_MAGIC_COOKIE, 4); 83 | stunRequest.writeUInt32BE(0, 8); 84 | stunRequest.writeUInt32BE(0, 12); 85 | stunRequest.writeUInt32BE(stunTxId, 16); 86 | 87 | socket.on('message', (msg) => { 88 | const xor = (a, b) => { 89 | const data = []; 90 | if (b.length > a.length) { 91 | const tmp = a; 92 | a = b; 93 | b = tmp; 94 | } 95 | for (let i = 0, len = a.length; i < len; i++) { 96 | data.push(a[i] ^ b[i]); 97 | } 98 | 99 | return new Buffer(data); 100 | }; 101 | 102 | const block = msg.readUInt8(0); 103 | const bit1 = block & 0x80; 104 | const bit2 = block & 0x40; 105 | 106 | if (!(bit1 === 0 && bit2 === 0)) { 107 | return; 108 | } 109 | 110 | const msgHeader = msg.slice(0, STUN_HEADER_LENGTH); 111 | const msgAttrs = msg.slice(STUN_HEADER_LENGTH, msg.length); 112 | 113 | let offset = 0; 114 | 115 | while (offset < msgAttrs.length) { 116 | const attrType = msgAttrs.readUInt16BE(offset); 117 | offset += 2; 118 | 119 | let attrBuffLength = msgAttrs.readUInt16BE(offset); 120 | const blockOut = attrBuffLength % 4; 121 | if (blockOut > 0) { 122 | attrBuffLength += 4 - blockOut; 123 | } 124 | offset += 2; 125 | 126 | const value = msgAttrs.slice(offset, offset + attrBuffLength); 127 | offset += attrBuffLength; 128 | 129 | let family; 130 | let address; 131 | switch (attrType) { 132 | case STUN_ATTR_MAPPED_ADDRESS: 133 | family = (value.readUInt16BE(0) === 0x02) ? 6 : 4; 134 | address = ip.toString(value, 4, family); 135 | addIPAddress(address); 136 | break; 137 | 138 | case STUN_ATTR_XOR_MAPPED_ADDRESS: 139 | case STUN_ATTR_XOR_MAPPED_ADDRESS_ALT: 140 | family = (value.readUInt16BE(0) === 0x02) ? 6 : 4; 141 | const magic = msgHeader.slice(4, 8); 142 | const tid = msgHeader.slice(8, 20); 143 | const xaddr = value.slice(4, family === 4 ? 8 : 20); 144 | const addr = xor(xaddr, family === 4 ? magic : value.concat([magic, tid])); 145 | address = ip.toString(addr, 0, family); 146 | addIPAddress(address); 147 | break; 148 | default: 149 | } 150 | } 151 | 152 | callback(stunIp); 153 | }); 154 | 155 | stunServers.map(([port, host]) => socket.send(stunRequest, 0, stunRequest.length, port, host, () => {})); 156 | } 157 | -------------------------------------------------------------------------------- /src/util/utils.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | /* eslint-disable no-param-reassign */ 3 | 4 | import type { BlinkTradeLevel, MsgTypes } from '../types'; 5 | 6 | const zipColumns = (arr: Array, columns: Array) => ( 7 | arr.reduce((prev, val, i) => { 8 | prev[columns[i]] = val; 9 | return prev; 10 | }, {}) 11 | ); 12 | 13 | export const msgToAction = (messages: MsgTypes) => { 14 | return Object.entries(messages).reduce((prev, val) => { 15 | // $FlowFixMe Fixed entries mixed type 16 | prev[val[1][0]] = val[0]; 17 | return prev; 18 | }, {}); 19 | }; 20 | 21 | export const formatColumns = (field: string, level: BlinkTradeLevel) => (data: Object) => { 22 | if (level === 2) { 23 | const list = data[field].map(row => zipColumns(row, data.Columns)); 24 | return Promise.resolve({ ...data, [field]: list }); 25 | } 26 | 27 | return Promise.resolve(data); 28 | }; 29 | 30 | export const formatBrokerList = (level: BlinkTradeLevel) => (data: Object) => { 31 | if (level === 2) { 32 | const BrokerListGrp = data.BrokerListGrp 33 | .map(row => zipColumns(row, data.Columns)) 34 | .reduce((prev, val) => { 35 | prev[val.BrokerID] = val; 36 | return prev; 37 | }, {}); 38 | 39 | return Promise.resolve({ ...data, BrokerListGrp }); 40 | } 41 | 42 | return Promise.resolve(data); 43 | }; 44 | 45 | export const formatTradeHistory = (level: BlinkTradeLevel) => (data: Object) => { 46 | if (level === 2) { 47 | const TradeHistoryGrp = data.TradeHistoryGrp 48 | .map(row => zipColumns(row, data.Columns)) 49 | .reduce((prev, val) => { 50 | (prev[val.Market] = prev[val.Market] || []).push(val); 51 | return prev; 52 | }, {}); 53 | 54 | return Promise.resolve({ ...data, TradeHistoryGrp }); 55 | } 56 | 57 | return Promise.resolve(data); 58 | }; 59 | 60 | export const formatOrderBook = (data: Object, level: BlinkTradeLevel) => { 61 | if (level === 2) { 62 | const { bids, asks } = data.MDFullGrp 63 | .filter(order => order.MDEntryType === '0' || order.MDEntryType === '1') 64 | .reduce((prev, order) => { 65 | const side = order.MDEntryType === '0' ? 'bids' : 'asks'; 66 | (prev[side] || (prev[side] = [])).push(order); 67 | return prev; 68 | }, []); 69 | 70 | return { 71 | ...data, 72 | MDFullGrp: { 73 | [data.Symbol]: { 74 | bids: bids || [], 75 | asks: asks || [], 76 | }, 77 | }, 78 | }; 79 | } 80 | 81 | return data; 82 | }; 83 | -------------------------------------------------------------------------------- /src/ws.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * @flow 21 | */ 22 | 23 | import os from 'os'; 24 | import nodeify from 'nodeify'; 25 | import { EventEmitter2 as EventEmitter } from 'eventemitter2'; 26 | import { generateRequestId } from './listener'; 27 | 28 | import type { 29 | Message, 30 | PromiseEmitter, 31 | BlinkTradeWSParams, 32 | BlinkTradeWSTransport, 33 | MarketDataParams, 34 | OrderBookSync, 35 | } from './types'; 36 | 37 | import { EVENTS } from './constants/utils'; 38 | import { 39 | BALANCE, 40 | DEPOSIT_REFRESH, 41 | WITHDRAW_REFRESH, 42 | EXECUTION_REPORT, 43 | } from './constants/actionTypes'; 44 | 45 | import { ActionMsgReq, ActionMsgRes } from './constants/messages'; 46 | import { 47 | formatOrderBook, 48 | formatTradeHistory, 49 | } from './util/utils'; 50 | 51 | import TradeBase from './trade'; 52 | import WebSocketTransport from './transports/websocket'; 53 | import { IS_NODE } from './transports/transport'; 54 | 55 | class BlinkTradeWS extends TradeBase { 56 | /** 57 | * Session to store login information 58 | */ 59 | session: Object; 60 | 61 | orderbook: OrderBookSync; 62 | syncReqId: number; 63 | isOrderBookSynced: boolean; 64 | 65 | transport: BlinkTradeWSTransport; 66 | 67 | constructor(params?: BlinkTradeWSParams = {}) { 68 | super(params); 69 | 70 | this.transport = params.transport || new WebSocketTransport(params); 71 | this.session = {}; 72 | this.orderbook = {}; 73 | this.isOrderBookSynced = false; 74 | this.syncReqId = 0; 75 | } 76 | 77 | connect(callback?: Function) { 78 | return this.emitterPromise(this.transport.connect(callback)); 79 | } 80 | 81 | disconnect() { 82 | return this.transport.disconnect(); 83 | } 84 | 85 | send(msg: Message): Promise { 86 | return this.transport.sendMessageAsPromise(msg); 87 | } 88 | 89 | on(event: string, callback: ?Function) { 90 | if (this.transport.eventEmitter) { 91 | return this.transport.eventEmitter.on(event, callback); 92 | } 93 | } 94 | 95 | emit(event: string, data: Object) { 96 | if (this.transport.eventEmitter) { 97 | return this.transport.eventEmitter.emit(event, data); 98 | } 99 | } 100 | 101 | emitterPromise(promise: Promise & Object, callback?: Function) { 102 | return this.transport.emitterPromise 103 | ? this.transport.emitterPromise(promise, callback) 104 | : promise; 105 | } 106 | 107 | heartbeat(callback?: Function): Promise { 108 | const d = new Date(); 109 | const msg: Message = { 110 | MsgType: ActionMsgReq.HEARTBEAT, 111 | TestReqID: generateRequestId(), 112 | SendTime: d.getTime(), 113 | }; 114 | 115 | return nodeify.extend(new Promise((resolve, reject) => { 116 | return this.send(msg).then(data => { 117 | return resolve({ 118 | ...data, 119 | Latency: new Date(Date.now()) - data.SendTime, 120 | }); 121 | }).catch(reject); 122 | })).nodeify(callback); 123 | } 124 | 125 | login({ username, password, secondFactor, cancelOnDisconnect, brokerId, ...extraData }: { 126 | username: string, 127 | password: string, 128 | secondFactor?: string, 129 | brokerId?: number, 130 | cancelOnDisconnect?: boolean, 131 | }, callback?: Function): Promise { 132 | let userAgent; 133 | if (!IS_NODE) { 134 | userAgent = { 135 | UserAgent: window.navigator.userAgent, 136 | UserAgentLanguage: window.navigator.language, 137 | UserAgentPlatform: window.navigator.platform, 138 | UserAgentTimezoneOffset: new Date().getTimezoneOffset(), 139 | }; 140 | } else { 141 | userAgent = { 142 | UserAgent: `${os.type()} ${os.release()}`, 143 | UserAgentLanguage: 'en_US', 144 | UserAgentPlatform: `${os.platform()} (${os.arch()})`, 145 | UserAgentTimezoneOffset: new Date().getTimezoneOffset(), 146 | }; 147 | } 148 | 149 | const msg: Message = { 150 | MsgType: ActionMsgReq.LOGIN, 151 | UserReqID: generateRequestId(), 152 | BrokerID: brokerId || this.brokerId, 153 | Username: username, 154 | Password: password, 155 | UserReqTyp: '1', 156 | CancelOnDisconnect: cancelOnDisconnect ? '1' : '0', 157 | ...userAgent, 158 | ...extraData, 159 | }; 160 | 161 | if (secondFactor) { 162 | msg.SecondFactor = secondFactor; 163 | } 164 | 165 | return nodeify.extend(new Promise((resolve, reject) => { 166 | return this.send(msg).then(data => { 167 | if (data.UserStatus === 1) { 168 | this.session = data; 169 | return resolve(data); 170 | } 171 | 172 | return reject(data); 173 | }).catch(reject); 174 | })).nodeify(callback); 175 | } 176 | 177 | logout(callback?: Function): Promise { 178 | const msg: Message = { 179 | MsgType: ActionMsgReq.LOGIN, 180 | BrokerID: this.brokerId, 181 | UserReqID: generateRequestId(), 182 | Username: this.session.Username, 183 | UserReqTyp: '2', 184 | }; 185 | 186 | return nodeify.extend(this.send(msg)).nodeify(callback); 187 | } 188 | 189 | profile(callback?: Function): Promise { 190 | const { VerificationData, ...profile } = this.session.Profile; 191 | return nodeify.extend(Promise.resolve(profile)).nodeify(callback); 192 | } 193 | 194 | balance(clientId?: string, callback?: Function): PromiseEmitter { 195 | return this.emitterPromise(new Promise((resolve, reject) => { 196 | return super.balance(clientId, callback).then((data) => { 197 | this.on(ActionMsgRes.BALANCE, (balance) => { 198 | callback && callback(null, balance); 199 | return this.emit(BALANCE, balance); 200 | }); 201 | return resolve(data); 202 | }).catch(reject); 203 | })); 204 | } 205 | 206 | onBalanceUpdate(callback: Function) { 207 | return this.on(ActionMsgRes.BALANCE, callback); 208 | } 209 | 210 | subscribeTicker(symbols: Array, callback?: Function): PromiseEmitter { 211 | const msg: Message = { 212 | MsgType: ActionMsgReq.SECURITY_STATUS_SUBSCRIBE, 213 | SecurityStatusReqID: generateRequestId(), 214 | SubscriptionRequestType: '1', 215 | Instruments: symbols, 216 | }; 217 | 218 | const formatTicker = (data) => ({ 219 | ...data, 220 | SellVolume: data.SellVolume / 1e8, 221 | LowPx: data.LowPx / 1e8, 222 | LastPx: data.LastPx / 1e8, 223 | BestAsk: data.BestAsk / 1e8, 224 | HighPx: data.HighPx / 1e8, 225 | BuyVolume: data.BuyVolume / 1e8, 226 | BestBid: data.BestBid / 1e8, 227 | }); 228 | 229 | return this.emitterPromise(new Promise((resolve, reject) => { 230 | return this.send(msg).then(data => { 231 | const event = ActionMsgRes.SECURITY_STATUS_SUBSCRIBE + ':' + data.SecurityStatusReqID; 232 | this.on(event, (ticker) => { 233 | const tickerFormatted = formatTicker(ticker); 234 | callback && callback(null, tickerFormatted); 235 | return this.emit(`${ticker.Market}:${ticker.Symbol}`, tickerFormatted); 236 | }); 237 | return resolve(formatTicker(data)); 238 | }).catch(reject); 239 | }), callback); 240 | } 241 | 242 | unSubscribeTicker(SecurityStatusReqID: number): number { 243 | const msg: Message = { 244 | MsgType: ActionMsgReq.SECURITY_STATUS_SUBSCRIBE, 245 | SubscriptionRequestType: '2', 246 | SecurityStatusReqID, 247 | }; 248 | 249 | this.transport.sendMessage(msg); 250 | return SecurityStatusReqID; 251 | } 252 | 253 | subscribeOrderbook(options: MarketDataParams, callback?: Function): PromiseEmitter { 254 | console.warn('Warning: subscribeOrderbook is DEPRECATED, use subscribeMarketData instead'); 255 | return this.subscribeMarketData(options, callback); 256 | } 257 | 258 | subscribeMarketData(options: MarketDataParams, callback?: Function): PromiseEmitter { 259 | const msg: Message = { 260 | MsgType: ActionMsgReq.MD_FULL_REFRESH, 261 | MDReqID: generateRequestId(), 262 | SubscriptionRequestType: '1', 263 | MarketDepth: 0, 264 | MDUpdateType: '1', // Incremental refresh 265 | MDEntryTypes: ['0', '1'], 266 | BrokerID: this.brokerId, 267 | }; 268 | 269 | if (Array.isArray(options)) { 270 | msg.Instruments = options; 271 | } else { 272 | msg.Instruments = options.instruments; 273 | msg.MDEntryTypes = options.entryTypes || msg.MDEntryTypes; 274 | msg.MarketDepth = options.marketDepth || msg.MarketDepth; 275 | } 276 | 277 | if (options.columns) { 278 | msg.Columns = options.columns; 279 | } 280 | 281 | const level = (!Array.isArray(options) && typeof options.level !== 'undefined') 282 | ? options.level 283 | : this.level; 284 | 285 | const subscribeEvent = (data) => { 286 | if (data.MDBkTyp === '3') { 287 | data.MDIncGrp.map(order => { 288 | switch (order.MDEntryType) { 289 | case '0': 290 | case '1': 291 | const orderbookEvent = `OB:${EVENTS.ORDERBOOK[order.MDUpdateAction]}`; 292 | const bidOfferData = { ...order, MDReqID: data.MDReqID, type: orderbookEvent }; 293 | 294 | callback && callback(null, bidOfferData); 295 | return this.emit(orderbookEvent, bidOfferData); 296 | case '2': 297 | const tradeEvent = `OB:${EVENTS.TRADES[order.MDUpdateAction]}`; 298 | const tradeData = { ...order, type: tradeEvent }; 299 | 300 | callback && callback(null, tradeData); 301 | return this.emit(tradeEvent, tradeData); 302 | case '4': 303 | break; 304 | default: 305 | return null; 306 | } 307 | return null; 308 | }); 309 | } 310 | }; 311 | 312 | return this.emitterPromise(new Promise((resolve, reject) => { 313 | return this.send(msg).then(data => { 314 | this.on(ActionMsgRes.MD_INCREMENT + ':' + data.MDReqID, subscribeEvent); 315 | return resolve(formatOrderBook(data, level)); 316 | }).catch(err => reject(err)); 317 | }), callback); 318 | } 319 | 320 | syncOrderbook(options: MarketDataParams): Promise { 321 | if (!this.isOrderBookSynced) { 322 | this.isOrderBookSynced = true; 323 | const sides = { '0': 'bids', '1': 'asks' }; 324 | const instruments = Array.isArray(options) ? options : options.instruments; 325 | return this.subscribeMarketData({ instruments, level: 2 }) 326 | .on('OB:NEW_ORDER', (order) => { 327 | if (order.MDReqID === this.syncReqId) { 328 | const index = order.MDEntryPositionNo - 1; 329 | this.orderbook[order.Symbol][sides[order.MDEntryType]].splice(index, 0, order); 330 | } 331 | }).on('OB:UPDATE_ORDER', (order) => { 332 | if (order.MDReqID === this.syncReqId) { 333 | const index = order.MDEntryPositionNo - 1; 334 | this.orderbook[order.Symbol][sides[order.MDEntryType]].splice(index, 1, order); 335 | } 336 | }).on('OB:DELETE_ORDER', (order) => { 337 | if (order.MDReqID === this.syncReqId) { 338 | const index = order.MDEntryPositionNo - 1; 339 | this.orderbook[order.Symbol][sides[order.MDEntryType]].splice(index, 1); 340 | } 341 | }).on('OB:DELETE_ORDERS_THRU', (order) => { 342 | if (order.MDReqID === this.syncReqId) { 343 | const index = order.MDEntryPositionNo; 344 | this.orderbook[order.Symbol][sides[order.MDEntryType]].splice(0, index); 345 | } 346 | }).then((data) => { 347 | this.syncReqId = data.MDReqID; 348 | this.orderbook = data.MDFullGrp; 349 | return this.orderbook; 350 | }); 351 | } 352 | return Promise.resolve(this.orderbook); 353 | } 354 | 355 | unSubscribeOrderbook(MDReqID: number): number { 356 | const msg: Message = { 357 | MsgType: ActionMsgReq.MD_FULL_REFRESH, 358 | MDReqID, 359 | MarketDepth: 0, 360 | SubscriptionRequestType: '2', 361 | }; 362 | 363 | this.transport.sendMessage(msg); 364 | return MDReqID; 365 | } 366 | 367 | executionReport(callback?: Function): EventEmitter { 368 | return this.on(ActionMsgRes.EXECUTION_REPORT, (data) => { 369 | callback && callback(data); 370 | const event = EVENTS.EXECUTION_REPORT[data.ExecType]; 371 | return this.emit(`${EXECUTION_REPORT}:${event}`, data); 372 | }); 373 | } 374 | 375 | tradeHistory({ since, symbols, page: Page = 0, pageSize: PageSize = 100 }: { 376 | since?: number, 377 | symbols?: Array, 378 | page?: number, 379 | pageSize?: number, 380 | } = {}, callback?: Function): Promise { 381 | const msg: Message = { 382 | MsgType: ActionMsgReq.TRADE_HISTORY, 383 | TradeHistoryReqID: generateRequestId(), 384 | Page, 385 | PageSize, 386 | }; 387 | 388 | if (symbols && symbols.length > 0) { 389 | msg.SymbolList = symbols; 390 | } 391 | 392 | if (since && typeof since === 'number') { 393 | msg.Since = since; 394 | } 395 | 396 | const format = formatTradeHistory(this.level); 397 | 398 | return nodeify.extend(this.send(msg).then(format)).nodeify(callback); 399 | } 400 | 401 | requestDeposit({ currency = 'BTC', value, depositMethodId }: { 402 | value?: number, 403 | currency?: string, 404 | depositMethodId?: number, 405 | } = {}, callback?: Function): PromiseEmitter { 406 | const subscribeEvent = (deposit) => { 407 | callback && callback(null, deposit); 408 | return this.emit(DEPOSIT_REFRESH, deposit); 409 | }; 410 | 411 | return this.emitterPromise(new Promise((resolve, reject) => { 412 | return super.requestDeposit({ currency, value, depositMethodId }).then(deposit => { 413 | const event = ActionMsgRes.DEPOSIT_REFRESH + ':' + deposit.ClOrdID; 414 | this.on(event, subscribeEvent); 415 | return resolve(deposit); 416 | }).catch(reject); 417 | }), callback); 418 | } 419 | 420 | onDepositRefresh(callback?: Function) { 421 | return this.on(ActionMsgRes.DEPOSIT_REFRESH, callback); 422 | } 423 | 424 | requestWithdraw({ amount, data, currency = 'BTC', method = 'bitcoin' }: { 425 | data: Object, 426 | amount: number, 427 | method?: string, 428 | currency?: string, 429 | }, callback?: Function): PromiseEmitter { 430 | const subscribeEvent = (withdraw) => { 431 | callback && callback(null, withdraw); 432 | return this.emit(WITHDRAW_REFRESH, withdraw); 433 | }; 434 | 435 | return this.emitterPromise(new Promise((resolve, reject) => { 436 | return super.requestWithdraw({ amount, data, currency, method }).then(withdraw => { 437 | this.on(ActionMsgRes.WITHDRAW_REFRESH + ':' + withdraw.ClOrdID, subscribeEvent); 438 | return resolve(withdraw); 439 | }).catch(reject); 440 | }), callback); 441 | } 442 | 443 | onWithdrawRefresh(callback?: Function) { 444 | return this.on(ActionMsgRes.WITHDRAW_REFRESH, callback); 445 | } 446 | } 447 | 448 | export default BlinkTradeWS; 449 | -------------------------------------------------------------------------------- /test/browser/browser.spec.js: -------------------------------------------------------------------------------- 1 | import { BlinkTradeWS } from '../../src'; 2 | 3 | jest.mock('../../src/util/fingerPrint'); 4 | 5 | describe('Browser environment', () => { 6 | test('Should match mock fingerprint', () => { 7 | const blinktrade = new BlinkTradeWS(); 8 | expect(blinktrade.transport.fingerPrint).toBe('MOCK_FINGERPRINT'); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /test/node/listener.spec.js: -------------------------------------------------------------------------------- 1 | import { 2 | reqs, 3 | setRequest, 4 | deleteRequest, 5 | generateRequestId, 6 | } from '../../src/listener'; 7 | 8 | let TestReqID = 0; 9 | 10 | const promise = { 11 | resolve: () => {}, 12 | reject: () => {}, 13 | }; 14 | 15 | describe('Request Listeners', () => { 16 | test('Register Request TestReqID', () => { 17 | TestReqID = generateRequestId(); 18 | setRequest({ MsgType: '1', TestReqID }, promise); 19 | expect(reqs.size).toBe(1); 20 | expect(reqs.get('TestReqID:' + TestReqID)).toEqual(promise); 21 | }); 22 | 23 | test('Register a second TestReqID', () => { 24 | TestReqID = generateRequestId(); 25 | setRequest({ MsgType: '1', TestReqID }, promise); 26 | expect(reqs.size).toBe(2); 27 | expect(reqs.get('TestReqID:' + TestReqID)).toEqual(promise); 28 | }); 29 | 30 | test('Delete Request from a response message', () => { 31 | deleteRequest({ MsgType: '0', TestReqID }); 32 | expect(reqs.size).toBe(1); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /test/node/node.spec.js: -------------------------------------------------------------------------------- 1 | import { BlinkTradeWS } from '../../src'; 2 | 3 | jest.mock('../../src/util/stun'); 4 | jest.mock('../../src/util/macaddress'); 5 | 6 | describe('Node environment', () => { 7 | test('Should match stunt mock', () => { 8 | const blinktrade = new BlinkTradeWS(); 9 | expect(blinktrade.transport.stun).toEqual({ local: null, public: [] }); 10 | blinktrade.transport.getStun(); 11 | expect(blinktrade.transport.stun).toBe('MOCK_STUN'); 12 | }); 13 | 14 | test('Should match macaddress mock', () => { 15 | const blinktrade = new BlinkTradeWS(); 16 | expect(blinktrade.transport.fingerPrint).toBe('MOCK_MACADDRESS'); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /test/node/rest.js: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import common from '../../src/constants/common'; 3 | import { BlinkTradeRest } from '../../src'; 4 | 5 | const endpoint = common.testnet.rest; 6 | 7 | const ticker = { 8 | high: 24091.21, 9 | vol: 65.30060763, 10 | buy: 24063.75, 11 | last: 24058.01, 12 | low: 23865.91, 13 | pair: 'BTCBRL', 14 | sell: 24091.21, 15 | vol_brl: 1566217.37416423, 16 | }; 17 | 18 | const tickerUSD = { 19 | high: 24000.0, 20 | vol: 0.00622652, 21 | buy: 24000.0, 22 | last: 24000.0, 23 | low: 24000.0, 24 | pair: 'BTCUSD', 25 | vol_usd: 149.43648, 26 | sell: 0, 27 | }; 28 | 29 | const balance = { 30 | Status: 200, 31 | Description: 'OK', 32 | Responses: [{ 33 | '4': { 34 | BTC_locked: 6051325, 35 | BRL: 25675952357074, 36 | BTC: 60136060, 37 | BRL_locked: 16307010000, 38 | }, 39 | MsgType: 'U3', 40 | ClientID: 90800078, 41 | BalanceReqID: 4904378, 42 | }], 43 | }; 44 | 45 | const errorResponse = { 46 | Status: 500, 47 | Description: 'Error', 48 | }; 49 | 50 | const sentOrder = { 51 | Status: 200, 52 | Description: 'OK', 53 | Responses: [ 54 | { 55 | OrderID: 999, 56 | ExecID: 0, 57 | ExecType: '0', 58 | OrdStatus: '0', 59 | LeavesQty: 10000000, 60 | Symbol: 'BTCBRL', 61 | OrderQty: 10000000, 62 | LastShares: 0, 63 | LastPx: 0, 64 | CxlQty: 0, 65 | TimeInForce: '1', 66 | CumQty: 0, 67 | MsgType: '8', 68 | ClOrdID: '999', 69 | OrdType: '2', 70 | Side: '1', 71 | Price: 500000000, 72 | ExecSide: '1', 73 | AvgPx: 0, 74 | }, 75 | { 76 | '4': { 77 | BTC_locked: 0, 78 | BRL: 10, 79 | BTC: 1, 80 | BRL_locked: 5, 81 | }, 82 | MsgType: 'U3', 83 | ClientID: 90800078, 84 | BalanceReqID: 4904378, 85 | }, 86 | ], 87 | }; 88 | 89 | const mockResponse = (uri, requestBody) => { 90 | const type = requestBody.MsgType; 91 | return type === 'U2' ? balance 92 | : type === 'D' ? sentOrder : errorResponse; 93 | }; 94 | 95 | const blinktrade = new BlinkTradeRest({ 96 | prod: false, 97 | key: '', 98 | secret: '', 99 | currency: 'BRL', 100 | }); 101 | 102 | describe('Rest', () => { 103 | test('GET /api/v1/BRL/ticker', async () => { 104 | nock(endpoint).get('/api/v1/BRL/ticker').reply(200, ticker); 105 | const data = await blinktrade.ticker(); 106 | expect(data).toEqual(ticker); 107 | }); 108 | 109 | test('GET /api/v1/USD/ticker', async () => { 110 | nock(endpoint).get('/api/v1/USD/ticker').reply(200, tickerUSD); 111 | const blinktrade = new BlinkTradeRest({ prod: false, currency: 'USD' }); 112 | const data = await blinktrade.ticker(); 113 | expect(data).toEqual(tickerUSD); 114 | }); 115 | 116 | test('POST /tapi/v1/message with balance request and matching signature headers', async () => { 117 | // Mock now to match the nonce signature 118 | Date.now = () => 1540356221059; 119 | nock(endpoint) 120 | .post('/tapi/v1/message') 121 | .matchHeader('content-type', 'application/json') 122 | .matchHeader('nonce', '1540356221059') 123 | .matchHeader('apikey', '') 124 | .matchHeader('signature', '0762599d1c3e25f9dd93f4c63669fc48db66b3816cb7f437edb4ecf2691a48bc') 125 | .reply(200, mockResponse); 126 | 127 | const data = await blinktrade.balance(); 128 | expect(data).toEqual(balance.Responses[0]); 129 | }); 130 | 131 | test('POST /tapi/v1/message and matching an array response', async () => { 132 | nock(endpoint).post('/tapi/v1/message').reply(200, mockResponse); 133 | const data = await blinktrade.sendOrder({}); 134 | expect(data).toEqual(sentOrder.Responses); 135 | }); 136 | 137 | test('POST /tapi/v1/message and replying with 500 stauts reponse and rejecting the promise', async () => { 138 | nock(endpoint).post('/tapi/v1/message').reply(200, mockResponse); 139 | try { 140 | await blinktrade.cancelOrder({}); 141 | } catch (error) { 142 | expect(error).toEqual(errorResponse); 143 | } 144 | }); 145 | }); 146 | -------------------------------------------------------------------------------- /test/node/websocket.spec.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BlinkTradeJS SDK 3 | * (c) 2016-present BlinkTrade, Inc. 4 | * 5 | * This file is part of BlinkTradeJS 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | /* eslint-disable new-cap */ 22 | 23 | import { BlinkTradeWS } from '../../src'; 24 | import { ActionMsgRes } from '../../src/constants/messages'; 25 | 26 | import mocks from '../../src/transports/__mocks__/messages'; 27 | 28 | jest.mock('../../src/transports/websocket'); 29 | 30 | let blinktrade; 31 | 32 | const incremental = ({ action = '0', type = '0', position = 2, MDReqID } = {}) => ({ 33 | MDReqID, 34 | MDBkTyp: '3', 35 | MsgType: 'X', 36 | MDIncGrp: [ 37 | { 38 | OrderID: 1459030505702, 39 | MDEntryPx: 1637400000000, 40 | MDUpdateAction: action, 41 | MDEntryTime: '22:34:12', 42 | Symbol: 'BTCBRL', 43 | UserID: 90800078, 44 | Broker: 'bitcambio', 45 | MDEntryType: type, 46 | MDEntryPositionNo: position, 47 | MDEntrySize: 100000000, 48 | MDEntryID: 1459030505702, 49 | MDEntryDate: '2018-07-17', 50 | }, 51 | ], 52 | }); 53 | 54 | const incrementalTrade = { 55 | MDReqID: 354590, 56 | MDBkTyp: '3', 57 | MsgType: 'X', 58 | MDIncGrp: [{ 59 | OrderID: 1459030505939, 60 | MDEntryPx: 27000000000000, 61 | TradeID: 20617, 62 | MDEntryBuyerID: 90800078, 63 | MDUpdateAction: '0', 64 | MDEntryTime: '00:01:01', 65 | Symbol: 'BTCBRL', 66 | SecondaryOrderID: 1459030449305, 67 | MDEntrySize: 100000, 68 | MDEntryType: '2', 69 | MDEntrySellerID: 90800027, 70 | MDEntryDate: '2018-07-18', 71 | Side: '1', 72 | type: 'OB:TRADE_NEW', 73 | }], 74 | }; 75 | 76 | const newOrder = { 77 | side: '1', 78 | price: parseInt(16374 * 1e8, 10), 79 | amount: parseInt(0.05 * 1e8, 10), 80 | symbol: 'BTCBRL', 81 | }; 82 | 83 | describe('WebSocket', () => { 84 | test('Should test getMac mock as node.js environment', () => { 85 | blinktrade = new BlinkTradeWS({ prod: false }); 86 | // console.log(blinktrade.transport).fib; 87 | expect('ha').toBe('ha'); 88 | }) 89 | test('Should connect on websocket and resolve a promise', (done) => { 90 | blinktrade = new BlinkTradeWS({ prod: false }); 91 | blinktrade.connect().then(({ connected }) => { 92 | expect(connected).toBe(true); 93 | return done(); 94 | }); 95 | }); 96 | 97 | test('Should connect on websocket receive open event', (done) => { 98 | blinktrade = new BlinkTradeWS({ prod: false }); 99 | const callback = jest.fn(); 100 | blinktrade.connect().on('OPEN', callback).then(() => { 101 | expect(callback).toBeCalled(); 102 | done(); 103 | }); 104 | }); 105 | 106 | test('Should connect on websocket receive a callback ', (done) => { 107 | blinktrade = new BlinkTradeWS({ prod: false }); 108 | blinktrade.connect((err, { connected }) => { 109 | expect(connected).toBe(true); 110 | expect(err).toBe(null); 111 | done(); 112 | }); 113 | }); 114 | 115 | test('Should send heartBeat message and mock ws response', (done) => { 116 | blinktrade = new BlinkTradeWS(); 117 | blinktrade.connect().then(() => blinktrade.heartbeat()).then((res) => { 118 | const { req } = blinktrade.transport; 119 | expect(res.Latency).toBe(req.SendTime - res.SendTime); 120 | done(); 121 | }).catch(done); 122 | }); 123 | 124 | test('Should send heartBeat message with callback', (done) => { 125 | blinktrade = new BlinkTradeWS(); 126 | blinktrade.connect().then(() => { 127 | blinktrade.heartbeat((err, res) => { 128 | const { req } = blinktrade.transport; 129 | expect(res.Latency).toBe(req.SendTime - res.SendTime); 130 | done(); 131 | }); 132 | }).catch(done); 133 | }); 134 | 135 | test('Should authenticate successfully ', (done) => { 136 | const data = { username: 'user', password: 'abc12345' }; 137 | blinktrade = new BlinkTradeWS(); 138 | blinktrade.connect().then(() => blinktrade.login(data)).then((res) => { 139 | expect(res.UserStatus).toBe(1); 140 | expect(res.Username).toBe(data.username); 141 | done(); 142 | }); 143 | }); 144 | 145 | test('Should reject authentication ', (done) => { 146 | const data = { username: 'user', password: 'wrongpassword' }; 147 | blinktrade = new BlinkTradeWS(); 148 | blinktrade.connect().then(() => blinktrade.login(data)).catch((res) => { 149 | expect(res.UserStatus).toBe(3); 150 | expect(res.Username).toBe(data.username); 151 | done(); 152 | }); 153 | }); 154 | 155 | test('Should login and logout successfully', (done) => { 156 | const data = { username: 'user', password: 'abc12345' }; 157 | blinktrade = new BlinkTradeWS(); 158 | blinktrade.connect().then(() => blinktrade.login(data)).then((res) => { 159 | expect(res.Username).toBe(data.username); 160 | expect(res.UserStatus).toBe(1); 161 | return blinktrade.logout(); 162 | }).then((res) => { 163 | expect(res.UserStatus).toBe(2); 164 | done(); 165 | }); 166 | }); 167 | 168 | test('Should request balance and match available balance', (done) => { 169 | blinktrade = new BlinkTradeWS(); 170 | blinktrade.connect().then(() => blinktrade.balance()).then((res) => { 171 | expect(res).toHaveProperty('4'); 172 | done(); 173 | }); 174 | }); 175 | 176 | test('Should subscribe on ticker', (done) => { 177 | blinktrade = new BlinkTradeWS(); 178 | blinktrade.connect() 179 | .then(() => blinktrade.subscribeTicker(['BLINK:BTCBRL'])) 180 | .then((res) => { 181 | const { req } = blinktrade.transport; 182 | expect(res).toEqual({ 183 | SellVolume: 6.0693, 184 | LowPx: 16437, 185 | LastPx: 16437, 186 | MsgType: 'f', 187 | BestAsk: 113700, 188 | HighPx: 16540, 189 | BuyVolume: 100333.9509, 190 | BestBid: 16437, 191 | Symbol: 'BTCBRL', 192 | SecurityStatusReqID: req.SecurityStatusReqID, 193 | Market: 'BLINK', 194 | }); 195 | done(); 196 | }); 197 | }); 198 | 199 | test('Should subscribe on ticker with callback', (done) => { 200 | blinktrade = new BlinkTradeWS(); 201 | blinktrade.connect().then(() => { 202 | blinktrade.subscribeTicker(['BLINK:BTCBRL'], (err, res) => { 203 | const { req } = blinktrade.transport; 204 | expect(res).toEqual({ 205 | SellVolume: 6.0693, 206 | LowPx: 16437, 207 | LastPx: 16437, 208 | MsgType: 'f', 209 | BestAsk: 113700, 210 | HighPx: 16540, 211 | BuyVolume: 100333.9509, 212 | BestBid: 16437, 213 | Symbol: 'BTCBRL', 214 | SecurityStatusReqID: req.SecurityStatusReqID, 215 | Market: 'BLINK', 216 | }); 217 | done(); 218 | }); 219 | }); 220 | }); 221 | 222 | test('Should get full orderbook with level 0', (done) => { 223 | blinktrade = new BlinkTradeWS({ level: 0 }); 224 | blinktrade.connect().then(() => blinktrade.subscribeMarketData(['BTCBRL'])).then((res) => { 225 | const { req } = blinktrade.transport; 226 | expect(res).toEqual(mocks.V(req)); 227 | done(); 228 | }).catch(err => done(err)); 229 | }); 230 | 231 | test('Should get full orderbook with level 2', (done) => { 232 | blinktrade = new BlinkTradeWS({ level: 2 }); 233 | blinktrade.connect().then(() => blinktrade.subscribeMarketData(['BTCBRL'])).then((res) => { 234 | const { req } = blinktrade.transport; 235 | const book = mocks.V(req).MDFullGrp; 236 | expect(res).toEqual({ 237 | MsgType: 'W', 238 | MDReqID: req.MDReqID, 239 | MarketDepth: 1000, 240 | Symbol: 'BTCBRL', 241 | MDFullGrp: { 242 | BTCBRL: { 243 | bids: [book[0], book[1]], 244 | asks: [book[2], book[3]], 245 | }, 246 | }, 247 | }); 248 | done(); 249 | }).catch(err => done(err)); 250 | }); 251 | 252 | test('Should get incremental orderbook updates and emit OB:NEW_ORDER with default level', (done) => { 253 | blinktrade = new BlinkTradeWS(); 254 | blinktrade.connect().then(() => { 255 | return blinktrade.subscribeMarketData(['BTCBRL']) 256 | .on('OB:NEW_ORDER', (res) => { 257 | expect(res.MDEntryPositionNo).toBe(2); 258 | expect(res.MDEntrySize).toBe(1 * 1e8); 259 | expect(res.MDEntryPx).toBe(16374 * 1e8); 260 | expect(res.MDEntryType).toBe('0'); 261 | expect(res.type).toBe('OB:NEW_ORDER'); 262 | done(); 263 | }); 264 | }).then(() => { 265 | const { req } = blinktrade.transport; 266 | blinktrade.transport.eventEmitter.emit(`${ActionMsgRes.MD_INCREMENT}:${req.MDReqID}`, incremental()); 267 | }); 268 | }); 269 | 270 | test('Should get incremental orderbook updates and emit OB:NEW_ORDER with level 0', (done) => { 271 | blinktrade = new BlinkTradeWS({ level: 0 }); 272 | blinktrade.connect().then(() => { 273 | return blinktrade.subscribeMarketData(['BTCBRL']) 274 | .on('OB:NEW_ORDER', (res) => { 275 | expect(res.MDEntryPositionNo).toBe(2); 276 | expect(res.MDEntrySize).toBe(100000000); 277 | expect(res.MDEntryPx).toBe(1637400000000); 278 | expect(res.MDEntryType).toBe('0'); 279 | expect(res.type).toBe('OB:NEW_ORDER'); 280 | done(); 281 | }); 282 | }).then(() => { 283 | const { req } = blinktrade.transport; 284 | blinktrade.transport.eventEmitter.emit(`${ActionMsgRes.MD_INCREMENT}:${req.MDReqID}`, incremental()); 285 | }); 286 | }); 287 | 288 | test('Should get incremental orderbook updates and emit OB:TRADE_NEW', (done) => { 289 | blinktrade = new BlinkTradeWS({ level: 0 }); 290 | blinktrade.connect().then(() => { 291 | return blinktrade.subscribeMarketData(['BTCBRL']) 292 | .on('OB:TRADE_NEW', (data) => { 293 | expect(data).toEqual({ 294 | ...incrementalTrade.MDIncGrp[0], 295 | type: 'OB:TRADE_NEW', 296 | }); 297 | done(); 298 | }); 299 | }).then(() => { 300 | const { req } = blinktrade.transport; 301 | blinktrade.transport.eventEmitter.emit(`${ActionMsgRes.MD_INCREMENT}:${req.MDReqID}`, incrementalTrade); 302 | }); 303 | }); 304 | 305 | test('Should send order and resolve promise', (done) => { 306 | blinktrade = new BlinkTradeWS(); 307 | blinktrade.connect().then(() => blinktrade.sendOrder(newOrder)).then((res) => { 308 | const { req } = blinktrade.transport; 309 | expect(res.ExecType).toBe('0'); 310 | expect(res.Price).toBe(1637400000000); 311 | expect(res.ClOrdID).toBe(req.ClOrdID); 312 | done(); 313 | }); 314 | }); 315 | 316 | test('Should send order and emit EXECUTION_REPORT:NEW', (done) => { 317 | blinktrade = new BlinkTradeWS(); 318 | blinktrade.executionReport().on('EXECUTION_REPORT:NEW', (res) => { 319 | const { req } = blinktrade.transport; 320 | expect(res.ExecType).toBe('0'); 321 | expect(res.Price).toBe(1637400000000); 322 | expect(res.ClOrdID).toBe(req.ClOrdID); 323 | done(); 324 | }); 325 | blinktrade.connect().then(() => blinktrade.sendOrder(newOrder)); 326 | }); 327 | 328 | test('Should send order and callback execution report', (done) => { 329 | blinktrade = new BlinkTradeWS(); 330 | 331 | const callback = jest.fn(); 332 | 333 | blinktrade.connect().then(() => { 334 | blinktrade.executionReport(callback); 335 | return blinktrade.sendOrder(newOrder); 336 | }).then(() => { 337 | expect(callback).toHaveBeenCalled(); 338 | done(); 339 | }); 340 | }); 341 | 342 | test('Should request a deposit and emit DEPOSIT_REFRESH event', (done) => { 343 | blinktrade = new BlinkTradeWS(); 344 | blinktrade.connect().then(() => { 345 | return blinktrade.requestDeposit().on('DEPOSIT_REFRESH', (res) => { 346 | const { req } = blinktrade.transport; 347 | expect(res.State).toBe('UNCONFIRMED'); 348 | expect(res.ClOrdID).toBe(req.ClOrdID); 349 | expect(res.DepositReqID).toBe(req.DepositReqID); 350 | done(); 351 | }); 352 | }).then((res) => { 353 | const { req } = blinktrade.transport; 354 | blinktrade.transport.eventEmitter.emit(`${ActionMsgRes.DEPOSIT_REFRESH}:${req.ClOrdID}`, res); 355 | }); 356 | }); 357 | 358 | test('Should request a withdraw and emit WITHDRAW_REFRESH event', (done) => { 359 | const data = { 360 | amount: 200 * 1e8, 361 | currency: 'BRL', 362 | method: 'PayPal', 363 | data: { 364 | Memo: 'Memo', 365 | email: 'user@blinktrade.com', 366 | }, 367 | }; 368 | 369 | blinktrade = new BlinkTradeWS(); 370 | blinktrade.connect().then(() => { 371 | return blinktrade.requestWithdraw(data).on('WITHDRAW_REFRESH', (res) => { 372 | const { req } = blinktrade.transport; 373 | expect(res.Status).toBe('1'); 374 | expect(res.ClOrdID).toBe(req.ClOrdID); 375 | expect(res.WithdrawReqID).toBe(req.WithdrawReqID); 376 | done(); 377 | }); 378 | }).then((res) => { 379 | const { req } = blinktrade.transport; 380 | blinktrade.transport.eventEmitter.emit(`${ActionMsgRes.WITHDRAW_REFRESH}:${req.ClOrdID}`, res); 381 | }); 382 | }); 383 | 384 | test('Should test syncOrderBook', (done) => { 385 | blinktrade = new BlinkTradeWS(); 386 | blinktrade.connect().then(() => { 387 | blinktrade.syncOrderbook(['BTCUSD']).then(() => { 388 | const { req } = blinktrade.transport; 389 | const { MDReqID } = req; 390 | const getOrder = (order) => ({ ...order.MDIncGrp[0], MDReqID, type: 'OB:NEW_ORDER' }); 391 | const book = mocks.V(req).MDFullGrp; 392 | const event = `${ActionMsgRes.MD_INCREMENT}:${req.MDReqID}`; 393 | const inc1 = incremental({ MDReqID, type: '0', position: 1 }); 394 | const inc2 = incremental({ MDReqID, type: '0', position: 2 }); 395 | const inc3 = incremental({ MDReqID, type: '1', position: 1 }); 396 | const inc4 = incremental({ MDReqID, type: '1', position: 2 }); 397 | const inc5 = incremental({ MDReqID, type: '1', action: '2', position: 1 }); 398 | const inc6 = incremental({ MDReqID, type: '0', action: '2', position: 1 }); 399 | const inc7 = incremental({ MDReqID, type: '0', action: '3', position: 2 }); 400 | const inc8 = incremental({ MDReqID: 0, type: '0', action: '0', position: 1 }); 401 | const order1 = getOrder(inc1); 402 | const order2 = getOrder(inc2); 403 | const order3 = getOrder(inc3); 404 | const order4 = getOrder(inc4); 405 | expect(blinktrade.orderbook).toEqual({ 406 | BTCBRL: { 407 | bids: [book[0], book[1]], 408 | asks: [book[2], book[3]], 409 | }, 410 | }); 411 | // Reset OrderBook 412 | blinktrade.orderbook = { BTCBRL: { bids: [], asks: [] }}; 413 | blinktrade.transport.eventEmitter.emit(event, inc1); 414 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1], asks: [] }}); 415 | blinktrade.transport.eventEmitter.emit(event, inc2); 416 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1, order2], asks: [] }}); 417 | blinktrade.transport.eventEmitter.emit(event, inc1); 418 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1, order1, order2], asks: [] }}); 419 | blinktrade.transport.eventEmitter.emit(event, inc4); 420 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1, order1, order2], asks: [order4] }}); 421 | blinktrade.transport.eventEmitter.emit(event, inc3); 422 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1, order1, order2], asks: [order3, order4] }}); 423 | blinktrade.transport.eventEmitter.emit(event, inc5); 424 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1, order1, order2], asks: [order4] }}); 425 | blinktrade.transport.eventEmitter.emit(event, inc6); 426 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [order1, order2], asks: [order4] }}); 427 | blinktrade.transport.eventEmitter.emit(event, inc7); 428 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [], asks: [order4] }}); 429 | // Ignore incrementals from different MDReqID 430 | blinktrade.transport.eventEmitter.emit(event, inc8); 431 | expect(blinktrade.orderbook).toEqual({ BTCBRL: { bids: [], asks: [order4] }}); 432 | done(); 433 | }); 434 | }); 435 | }); 436 | }); 437 | --------------------------------------------------------------------------------