├── .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