├── COPYING ├── COPYING.LESSER ├── LICENCE ├── README ├── ROADMAP ├── app.yaml ├── appdb └── appdb.go ├── arbit ├── arbit.go └── settings.go ├── arbitrage ├── arbitrage.go └── arbitragetest.go ├── campbx ├── campbx.go └── campbxapi.go ├── cron.yaml ├── mtgox ├── mtgox.go └── mtgoxapi.go ├── restapi └── restapi.go ├── tradehill ├── tradehill.go └── tradehillapi.go └── xgen ├── exchange.go └── tradeaccount.go /COPYING: -------------------------------------------------------------------------------- 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 | 635 | Copyright (C) 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 | Copyright (C) 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 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 Teppo Salonen 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | UPDATE 2012-05-06: After TradeHill shut down it's operations on 2012-02-13, and ExchB had already closed it's doors earlier, this software is no longer functional as it is (as you cannot do arbitrage with only one Bitcoin exchange). 2 | 3 | At this time I have no further plans on continuing the development of ArBit. Therefore I am also changing the licence to MIT/X11 (from LGPLv3), so feel free to modify it to your needs or incorporate the ideas to your own trading algorithms. 4 | 5 | == About ArBit == 6 | 7 | ArBit is an automated Bitcoin arbitrage trading program implemented in Go and written using Google App Engine SDK. It currently supports Mt Gox and TradeHill. (ExchB was also supported until the site was closed down.) 8 | 9 | I started writing ArBit after being impressed by the concept of so called "crypto currencies", and writing an arbitrage engine sounded like a non-trivial yet small enough project I could use for learning Go. And though I'm not a big believer in Bitcoin per se (the poor economic design alone begs for the project to be forked), it's technology is very promising and it has shown that digital currencies in general have a lot of potential. 10 | 11 | This is also my first ever open source contribution, so it is mostly a personal experiment with a primary goal of making myself a better programmer, and at the same time hopefully being useful to someone else too. I wrote the program in Go because it was the one language I really wanted to learn, and the reason for using the App Engine SDK was that it just made it so much easier to get started. 12 | 13 | The project is made of several packages containing the arbitrage engine, API functions for connecting to various Bitcoin exchanges, basic methods for storing data in the App Engine datastore, etc. They are all distributed under an MIT-style license. 14 | 15 | 16 | == Installation == 17 | 18 | In order to run ArBit on your local machine, you will need to download and install 'Google App Engine SDK for GO' at: 19 | http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Go 20 | 21 | (I have only used the Linux 32-bit version and installed it on Ubuntu 11.04, so I don't know how easy it would be to set it up for Mac OS for example. Notice also, that you do *not* need to have Go installed prior to this step, as the App Engine SDK is "fully self-contained".) 22 | 23 | If you are using Linux like myself (Ubuntu 11.04), you can start the local App Engine server with the following command (just replace /path/to/ with the correct directory): 24 | /path/to/google_appengine/dev_appserver.py /path/to/ArBit 25 | 26 | And I actually also created the following launcher on my desktop (you might need to modify this depending on your setup): 27 | gnome-terminal -e "/path/to/google_appengine/dev_appserver.py /path/to/ArBit" 28 | 29 | And finally when the local App Engine server is running, I added the following line in my crontab to fully automate the arbitrage trading (by running ArBit once a minute): 30 | 31 | * * * * * curl localhost:8080/cron/ 32 | 33 | Alternatively you could upload the application to Google's App Engine servers (http://code.google.com/appengine/docs/go/gettingstarted/uploading.html), or even try using it with AppScale (http://code.google.com/p/appscale/). But if you do upload it to App Engine you cannot use crontab as described above, and will need to set up the cron job based on the info on: http://code.google.com/appengine/docs/python/config/cron.html 34 | 35 | 36 | == FAQ == 37 | 38 | Q: Does it really make profit risk-free? 39 | 40 | A: In theory, yes. Each arbitrage trade executed makes immediate profit risk-free (not considering external risks such as part of the trade failing to fill due to a technical error, inaccurate data from the exchange, or maybe another trader executing the same trade faster). 41 | 42 | In practice however, the process requires you to maintain a positive balance of both BTC and USD in your accounts, and that will expose you to an exchange rate risk that can be much higher than the expected profit from the arbitrage. Therefore any decline in the BTC prices would cause the dollar value of your portfolio to decline as well, and vice versa. 43 | 44 | Q: Do arbitrage opportunities really exist? 45 | 46 | At the time of writing this, there seems to be enough arbitrage opportunities available that even a slow once-per-minute strategy finds them pretty much every day. 47 | 48 | But it is obvious that there are other arbitrage traders out there, so the opportunities are relatively small, won't last for too long, and mostly appear during short rallies (up or down) where one exchange moves faster than the other. And of course, open source projects such as this one are only going to make the competition tougher. 49 | 50 | UPDATE 2011-10-20: After ExchB was shut down on 2011-10-16, the number of available arbitrage opportunities has dropped significantly. 51 | 52 | 53 | == Author == 54 | 55 | Teppo Salonen 56 | 57 | -------------------------------------------------------------------------------- /ROADMAP: -------------------------------------------------------------------------------- 1 | PRESENT: 2 | 3 | ArBit is at it's version 0.11, which is an alpha release. 4 | 5 | 6 | Known issues: 7 | 8 | 1. Support for Camp BX is otherwise complete but json.Unmarshal fails for some reason (maybe due to whitespaces in the field names?) 9 | 10 | 2. Error/warning messages returned by the exchanges are ignored - for example: 11 | - TradeHill can return a JSON element "error" with messages such as "The smallest allowable transaction size is 1.00 USD." 12 | 13 | 14 | FUTURE: 15 | 16 | Arbit 1.0 is planned to be released by the end of 2012 with all known issues fixed and TODO items completed across the files. Other planned features include: Automated BTC transfers between exchanges, using Websocket API for realtime market data (instead of current once-per-minute polling), not requiring Google App Engine SDK, and using goroutines for concurrent API calls (which I had actually implemented already but since the App Engine runs only one thread, there was no difference in execution time in GAE). 17 | 18 | More Bitcoin exchanges (such as Bitcoinica) will be added. And eventually other digital currencies may also be added, but legitimate alternatives to Bitcoin need to be developed first and be traded on the major exchanges. (Nonsensical forks like Ixcoin do not qualify.) 19 | 20 | In addition to pure arbitrage, a more complete trading platform that makes it easy to write and backtest custom technical indicators and trading strategies may also be created. 21 | 22 | -------------------------------------------------------------------------------- /app.yaml: -------------------------------------------------------------------------------- 1 | application: arbit 2 | version: 1 3 | runtime: go 4 | api_version: 3 5 | 6 | handlers: 7 | - url: /cron/ 8 | script: _go_app 9 | #login: admin 10 | #auth_fail_action: unauthorized 11 | 12 | - url: /dashboard/ 13 | script: _go_app 14 | login: required 15 | 16 | - url: /.* 17 | script: _go_app 18 | 19 | -------------------------------------------------------------------------------- /appdb/appdb.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package appdb implements basic functions for storing and retrieving data from Google App Engine's datastore. 5 | package appdb 6 | 7 | // TODO: |filterStr| and |filterVal| not used in |Query| 8 | 9 | import ( 10 | "appengine" 11 | "appengine/datastore" 12 | "os" 13 | ) 14 | 15 | type UniqueKeyer interface { 16 | UniqueKey() (string, int64) 17 | } 18 | 19 | // Put creates or updates a datastore entity of given kind - the entity is stored in |data| and implements interface |UniqueKeyer|. 20 | func Put(c appengine.Context, kind string, data UniqueKeyer) (err os.Error) { 21 | stringId, intId := data.UniqueKey() 22 | key := datastore.NewKey(c, kind, stringId, intId, nil) 23 | _, err = datastore.Put(c, key, data) 24 | return 25 | } 26 | 27 | // KeyPut creates or updates a datastore entity of given kind - the entity is stored in |data| and has a unique key either in |sKey| or in |iKey|. 28 | func KeyPut(c appengine.Context, kind string, data interface{}, sKey string, iKey int64) (err os.Error) { 29 | key := datastore.NewKey(c, kind, sKey, iKey, nil) 30 | _, err = datastore.Put(c, key, data) 31 | return 32 | } 33 | 34 | // Get retrieves a datastore entity of given kind based on the unique key found in |data|, and stores the entity back to |data|. 35 | func Get(c appengine.Context, kind string, data UniqueKeyer) (err os.Error) { 36 | stringId, intId := data.UniqueKey() 37 | key := datastore.NewKey(c, kind, stringId, intId, nil) 38 | err = datastore.Get(c, key, data) 39 | return 40 | } 41 | 42 | // KeyGet retrieves a datastore entity of given kind based on the unique key in either |sKey| or |iKey|, and stores the entity to |data|. 43 | func KeyGet(c appengine.Context, kind string, data interface{}, sKey string, iKey int64) (err os.Error) { 44 | key := datastore.NewKey(c, kind, sKey, iKey, nil) 45 | err = datastore.Get(c, key, data) 46 | return 47 | } 48 | 49 | // Query retrieves datastore entities of given kind. 50 | func Query(c appengine.Context, kind string, filterStr string, filterVal interface{}, 51 | order string, offset int, limit int) (data []datastore.Map, err os.Error) { 52 | q := datastore.NewQuery(kind) 53 | if order != "" { 54 | q = q.Order(order) 55 | } 56 | q = q.Offset(offset).Limit(limit) 57 | data = make([]datastore.Map, 0) 58 | _, err = q.GetAll(c, &data) 59 | return 60 | } 61 | 62 | // Delete deletes a datastore entity of given kind based on the unique key found in |data|. 63 | func Delete(c appengine.Context, kind string, data UniqueKeyer) (err os.Error) { 64 | stringId, intId := data.UniqueKey() 65 | key := datastore.NewKey(c, kind, stringId, intId, nil) 66 | err = datastore.Delete(c, key) 67 | return 68 | } 69 | -------------------------------------------------------------------------------- /arbit/arbit.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This program is distributed under the terms of the MIT/X11 license. 3 | 4 | // Package arbit is the "main" package of ArBit. 5 | package arbit 6 | 7 | // TODO: Send out an email with the arbitrage strategy executed? 8 | // TODO: Show the list of executed trades and calculated strategies in the dashboard (current dahsboard is pretty useless) 9 | // TODO: Replace hardcoded 500ms delays between API calls with exchange specific sleep times (100ms for TradeHill, 500ms for CampBX, etc) 10 | // TODO: Improve debugging, logging, and add more data to the dashboard 11 | 12 | import ( 13 | "os" 14 | "fmt" 15 | "http" 16 | "xgen" 17 | "mtgox" 18 | "tradehill" 19 | // "campbx" 20 | "appdb" 21 | "arbitrage" 22 | "time" 23 | "appengine" 24 | "appengine/datastore" 25 | ) 26 | 27 | // Bitcoin exchanges to be used for arbitrage 28 | const ( 29 | mtGox = iota 30 | tradeHill 31 | // campBx 32 | // bitcoinica 33 | 34 | numExchanges 35 | ) 36 | 37 | var exchangeName = [numExchanges]string{"MtGox", "TradeHill" /*, "CampBX", "Bitcoinica"*/ } 38 | 39 | var login [numExchanges]xgen.Credentials 40 | 41 | var commission [numExchanges]float64 // Commission per trade (by exchange) 42 | var minTrade [numExchanges][xgen.NumCurrencies]float64 // Minimum transaction size (by exchange by currency) 43 | 44 | var onesidedArb bool // Take one side of an arbitrage even if not enough funds on the other account (used for balancing USD and BTC within the account) 45 | var paperTrade bool // In Paper Trade mode trades will not be executed 46 | 47 | func init() { 48 | http.HandleFunc("/cron/", errorHandlerLog(cronjob)) 49 | http.HandleFunc("/dashboard/", errorHandlerWeb(dashboard)) 50 | http.HandleFunc("/testing/", errorHandlerWeb(unittests)) 51 | } 52 | 53 | func errorHandlerLog(fn http.HandlerFunc) http.HandlerFunc { 54 | return func(w http.ResponseWriter, r *http.Request) { 55 | defer func() { 56 | if e, ok := recover().(os.Error); ok { 57 | c := appengine.NewContext(r) 58 | c.Criticalf(e.String()) 59 | } 60 | }() 61 | fn(w, r) 62 | } 63 | } 64 | 65 | func errorHandlerWeb(fn http.HandlerFunc) http.HandlerFunc { 66 | return func(w http.ResponseWriter, r *http.Request) { 67 | defer func() { 68 | if e, ok := recover().(os.Error); ok { 69 | w.WriteHeader(500) 70 | fmt.Fprintln(w, e) 71 | } 72 | }() 73 | fn(w, r) 74 | } 75 | } 76 | 77 | func check(err os.Error) { 78 | if err != nil { 79 | panic(err) 80 | } 81 | } 82 | 83 | func dashboard(w http.ResponseWriter, r *http.Request) { // Simple monitoring dashboard 84 | //var err os.Error 85 | c := appengine.NewContext(r) 86 | 87 | fmt.Fprintln(w, "") 88 | fmt.Fprintln(w, "") 89 | 90 | // Read ticker data from datastore 91 | var ticker [numExchanges][]datastore.Map 92 | for i := int8(0); i < numExchanges; i++ { 93 | ticker[i], _ = appdb.Query(c, "Ticker_"+exchangeName[i], "", nil, "-Date", 0, 1) // Get the last ticker only 94 | fmt.Fprintln(w, "") 96 | } 97 | fmt.Fprintln(w, "
ExchangeUpdatedHighest BuyLowest SellLast Trade
", exchangeName[i], "", time.SecondsToLocalTime(int64(ticker[i][0]["Date"].(datastore.Time))/1e6), 95 | "", ticker[i][0]["HighestBuy"], "", ticker[i][0]["LowestSell"], "", ticker[i][0]["Last"], "
") 98 | } 99 | 100 | func cronjob(w http.ResponseWriter, r *http.Request) { // Main program (to be run as a cron job) 101 | var err os.Error 102 | c := appengine.NewContext(r) 103 | 104 | // Quotes/Tickers by exchange 105 | var quote [numExchanges]xgen.Quote 106 | quote[mtGox], err = mtgox.GetQuote(c) 107 | check(err) 108 | quote[tradeHill], err = tradehill.GetQuote(c) 109 | check(err) 110 | // quote[campBx], err = campbx.GetQuote(c) // For some reason the Unmarshal in GetJson function in api.go causes: "runtime error: invalid memory address or nil pointer dereference" 111 | // check(err) 112 | 113 | // Store ticker data in datastore 114 | for i := int8(0); i < numExchanges; i++ { 115 | err = appdb.KeyPut(c, "Ticker_"+exchangeName[i], "e[i], "", time.Seconds()) 116 | check(err) 117 | } 118 | 119 | // Check if arbitrage exists 120 | var maxBid, minAsk float64 121 | for ex, q := range quote { 122 | bid := q.HighestBuy * (1 - commission[ex]) 123 | if maxBid == 0 || bid > maxBid { 124 | maxBid = bid 125 | } 126 | ask := q.LowestSell / (1 - commission[ex]) 127 | if minAsk == 0 || ask < minAsk { 128 | minAsk = ask 129 | } 130 | } 131 | if maxBid < minAsk { 132 | fmt.Fprintln(w, "No Arbitrage Exists: Highest Buy ", maxBid, " < Lowest Sell ", minAsk, "
") 133 | return 134 | } 135 | 136 | time.Sleep(0.5 * 1e9) // Wait for half a second before the next API calls 137 | 138 | // Account balances by exchange 139 | var funds [numExchanges]xgen.Balance 140 | funds[mtGox], err = mtgox.GetBalance(c, login[mtGox]) 141 | check(err) 142 | funds[tradeHill], err = tradehill.GetBalance(c, login[tradeHill]) 143 | check(err) 144 | // funds[campBx], err = campbx.GetBalance(c, login[campBx]) 145 | // check(err) 146 | 147 | time.Sleep(0.5 * 1e9) // Wait for half a second before the next API calls 148 | 149 | // Open orders by exchange 150 | var pending [numExchanges]xgen.OpenOrders 151 | pending[mtGox], err = mtgox.GetOpenOrders(c, login[mtGox]) 152 | check(err) 153 | pending[tradeHill], err = tradehill.GetOpenOrders(c, login[tradeHill]) 154 | check(err) 155 | // pending[campBx], err = campbx.GetOpenOrders(c, login[campBx]) 156 | // check(err) 157 | 158 | time.Sleep(0.5 * 1e9) // Wait for half a second before the next API calls 159 | 160 | // Cancel any open orders 161 | for i := int8(0); i < numExchanges; i++ { 162 | for oid, _ := range pending[i].Buy { 163 | if !paperTrade { 164 | switch i { 165 | case mtGox: 166 | _, err = mtgox.CancelOrder(c, login[i], oid, 2) 167 | case tradeHill: 168 | _, err = tradehill.CancelOrder(c, login[i], oid) 169 | // case campBx: _, err = campbx.CancelOrder(c, login[i], oid, "Buy") 170 | } 171 | check(err) 172 | // Store the canceled order in datastore 173 | err = appdb.KeyPut(c, "Cancel_"+exchangeName[i], &pending[i].Buy, "", time.Seconds()) 174 | check(err) 175 | time.Sleep(0.5 * 1e9) // Wait for half a second before the next API calls 176 | } 177 | } 178 | for oid, _ := range pending[i].Sell { 179 | if !paperTrade { 180 | switch i { 181 | case mtGox: 182 | _, err = mtgox.CancelOrder(c, login[i], oid, 1) 183 | case tradeHill: 184 | _, err = tradehill.CancelOrder(c, login[i], oid) 185 | // case campBx: _, err = campbx.CancelOrder(c, login[i], oid, "Sell") 186 | } 187 | check(err) 188 | // Store the canceled order in datastore 189 | err = appdb.KeyPut(c, "Cancel_"+exchangeName[i], &pending[i].Sell, "", time.Seconds()) 190 | check(err) 191 | time.Sleep(0.5 * 1e9) // Wait for half a second before the next API calls 192 | } 193 | } 194 | } 195 | 196 | // Limit order books by exchange 197 | var book [numExchanges]xgen.OrderBook 198 | book[mtGox], err = mtgox.GetOrderBook(c) 199 | check(err) 200 | book[tradeHill], err = tradehill.GetOrderBook(c) 201 | check(err) 202 | // book[campBx], err = campbx.GetOrderBook(c) 203 | // check(err) 204 | 205 | // Find the arbitrage strategy 206 | strategy := arbitrage.Calculate(book[:], funds[:], commission[:], minTrade[:]) 207 | 208 | // Check for internal arbitrage within the same exchange, since those should not happen if the data is correct and the exchange is working correctly 209 | for i := int8(0); i < numExchanges; i++ { 210 | if strategy.Buy[i].Amount > 0 && strategy.Sell[i].Amount > 0 { 211 | panic(fmt.Sprintln("Arbitrage within", exchangeName[i], "order books")) 212 | } 213 | } 214 | 215 | // If one-sided trades allowed, use them for balancing the total USD and BTC within accounts 216 | if onesidedArb { 217 | strategy = arbitrage.Onesided(strategy, funds[:], commission[:]) 218 | } 219 | 220 | time.Sleep(0.5 * 1e9) // One second is 1e9 nanoseconds 221 | 222 | // Execute trades 223 | for i := int8(0); i < numExchanges; i++ { 224 | if strategy.Buy[i].Amount > 0 { 225 | fmt.Fprintln(w, exchangeName[i], ": Buy", strategy.Buy[i].Amount, "bitcoins for", strategy.Buy[i].Price, "USD per BTC
") 226 | 227 | // Execute trade: 228 | if !paperTrade { 229 | switch i { 230 | case mtGox: 231 | _, err = mtgox.Buy(c, login[i], strategy.Buy[i].Price, strategy.Buy[i].Amount) 232 | case tradeHill: 233 | _, err = tradehill.Buy(c, login[i], strategy.Buy[i].Price, strategy.Buy[i].Amount) 234 | // case campBx: _, err = campbx.Buy(c, login[i], strategy.Buy[i].Price, strategy.Buy[i].Amount) 235 | } 236 | check(err) 237 | // Store the order in datastore 238 | err = appdb.KeyPut(c, "Buy_"+exchangeName[i], &strategy.Buy[i], "", time.Seconds()) 239 | check(err) 240 | } 241 | } else if strategy.Sell[i].Amount > 0 { 242 | fmt.Fprintln(w, exchangeName[i], ": Sell", strategy.Sell[i].Amount, "bitcoins for", strategy.Sell[i].Price, "USD per BTC
") 243 | 244 | // Execute trade: 245 | if !paperTrade { 246 | switch i { 247 | case mtGox: 248 | _, err = mtgox.Sell(c, login[i], strategy.Sell[i].Price, strategy.Sell[i].Amount) 249 | case tradeHill: 250 | _, err = tradehill.Sell(c, login[i], strategy.Sell[i].Price, strategy.Sell[i].Amount) 251 | // case campBx: _, err = campbx.Sell(c, login[i], strategy.Sell[i].Price, strategy.Sell[i].Amount) 252 | } 253 | check(err) 254 | // Store the order in datastore 255 | err = appdb.KeyPut(c, "Sell_"+exchangeName[i], &strategy.Sell[i], "", time.Seconds()) 256 | check(err) 257 | } 258 | } else { 259 | fmt.Fprintln(w, "No arbirage opportunities at:", exchangeName[i], "
") 260 | } 261 | fmt.Fprintln(w, exchangeName[i], ": Bid", book[i].BuyTree[0].Price*(1-commission[i]), "Ask", 262 | book[i].SellTree[0].Price/(1-commission[i]), "

") 263 | } 264 | } 265 | 266 | func unittests(w http.ResponseWriter, r *http.Request) { // Delete and use 'gotest' instead! 267 | err := arbitrage.TestCalculate() 268 | if err != nil { 269 | fmt.Fprintln(w, err.String()) 270 | } else { 271 | fmt.Fprintln(w, "arbitrage.Calculate: OK
") 272 | } 273 | 274 | err = arbitrage.TestOnesided() 275 | if err != nil { 276 | fmt.Fprintln(w, err.String()) 277 | } else { 278 | fmt.Fprintln(w, "arbitrage.TestOnesided: OK
") 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /arbit/settings.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This program is distributed under the terms of the MIT/X11 license. 3 | 4 | package arbit 5 | 6 | import "xgen" 7 | 8 | func init() { 9 | // Login credentials 10 | login[mtGox] = xgen.Credentials{Username: "", Password: ""} 11 | login[tradeHill] = xgen.Credentials{Username: "", Password: ""} 12 | // login[campBx] = xgen.Credentials{Username: "", Password: ""} 13 | // login[bitcoinica] = xgen.Credentials{Username: "", Password: ""} 14 | 15 | // Commissions per trade (volume discounts may be available, so adjust these to reflect your commission level) 16 | commission[mtGox] = 0.0060 // MtGox commission without volume discounts is currently 0.6% (=0.0060) 17 | commission[tradeHill] = 0.0060 * 0.9 // TradeHill commissions reduced by 10% if account is created via referral code/link 18 | // commission[campBx] = 0.0055 * 0.9 // CampBX commissions reduced by 10% if account is created via referral code/link 19 | // commission[bitcoinica] = 0 // Bitcoinica doesn't have a fixed commission - they adjust the spread between buy and sell instead 20 | 21 | /* 22 | If you don't have referral codes for TradeHill or CampBX but want to get the reduced commissions, feel free to use these: 23 | TradeHill: TH-R115773 24 | CampBX: https://CampBX.com/register.php?r=IPxoWpqzIq0 25 | Disclaimer! If you do use either of these codes, I will also receive 10% of the commissions you generate. 26 | */ 27 | 28 | // Minimum transaction sizes 29 | minTrade[mtGox][xgen.USD] = 0.01 30 | minTrade[mtGox][xgen.BTC] = 0.01 31 | minTrade[tradeHill][xgen.USD] = 1 // TradeHill's minimum transaction size is $1 32 | minTrade[tradeHill][xgen.BTC] = 0 33 | // minTrade[campBx][xgen.USD] = 0 34 | // minTrade[campBx][xgen.BTC] = 0.1 // CampBX's minimum transaction size is 0.1 BTC 35 | // minTrade[bitcoinica][xgen.USD] = 0.02 36 | // minTrade[bitcoinica][xgen.BTC] = 0.02 // Bitcoinica's minimum transaction size is 0.02 units 37 | 38 | onesidedArb = true 39 | paperTrade = false // Set true for testing/debugging only 40 | } 41 | -------------------------------------------------------------------------------- /arbitrage/arbitrage.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package arbitrage implements functions for calculating Bitcoin arbitrage strategies. 5 | package arbitrage 6 | 7 | import ( 8 | "xgen" 9 | "sort" 10 | // "math" 11 | ) 12 | 13 | // Strategy is a struct for storing the calculated trading strategy. 14 | type Strategy struct { 15 | Buy []xgen.Order 16 | Sell []xgen.Order 17 | } 18 | 19 | type arbOrder struct { 20 | order xgen.Order 21 | exchange int8 22 | } 23 | type arbOrders []arbOrder 24 | type arbOrderBook struct { // Master limit order book (after combining limit orders from all exchanges) 25 | buyTree arbOrders 26 | sellTree arbOrders 27 | } 28 | 29 | func (m arbOrders) Len() int { return len(m) } 30 | func (m arbOrders) Less(i, j int) bool { return m[i].order.Price < m[j].order.Price } 31 | func (m arbOrders) Swap(i, j int) { m[i], m[j] = m[j], m[i] } 32 | 33 | func (m arbOrders) Reverse() { 34 | for i, j := 0, len(m)-1; i < j; i, j = i+1, j-1 { 35 | m[i], m[j] = m[j], m[i] 36 | } 37 | } 38 | 39 | // Calculate calculates an optimal arbitrage strategy. 40 | func Calculate(book []xgen.OrderBook, funds []xgen.Balance, commission []float64, minTrade [][xgen.NumCurrencies]float64) (arb Strategy) { 41 | arb.Buy = make([]xgen.Order, len(book)) 42 | arb.Sell = make([]xgen.Order, len(book)) 43 | 44 | // Combine all order books into one 45 | var arbBook arbOrderBook 46 | for i, b := range book { 47 | if !b.Validate() { 48 | continue 49 | } 50 | for _, o := range b.BuyTree { 51 | var a arbOrder 52 | a.order = o 53 | a.exchange = int8(i) 54 | arbBook.buyTree = append(arbBook.buyTree, a) 55 | } 56 | for _, o := range b.SellTree { 57 | var a arbOrder 58 | a.order = o 59 | a.exchange = int8(i) 60 | arbBook.sellTree = append(arbBook.sellTree, a) 61 | } 62 | } 63 | sort.Sort(arbBook.buyTree) 64 | sort.Sort(arbBook.sellTree) 65 | arbBook.buyTree.Reverse() 66 | 67 | fundsLeft := make([]xgen.Balance, len(funds)) 68 | copy(fundsLeft, funds) 69 | 70 | // Find the arbitrage trades 71 | buyer, seller := 0, 0 72 | buyerExchange := arbBook.buyTree[buyer].exchange 73 | sellerExchange := arbBook.sellTree[seller].exchange 74 | buyerAmount := arbBook.buyTree[buyer].order.Amount 75 | sellerAmount := arbBook.sellTree[seller].order.Amount 76 | for arbBook.buyTree[buyer].order.Price*(1-commission[buyerExchange]) > arbBook.sellTree[seller].order.Price/(1-commission[sellerExchange]) { 77 | // If not enough BTC in the account for the minimum allowed trade size (sell), it's the same as if the account was empty of BTC 78 | if fundsLeft[buyerExchange][xgen.BTC] < minTrade[buyerExchange][xgen.BTC] || 79 | fundsLeft[buyerExchange][xgen.BTC] < minTrade[buyerExchange][xgen.USD]/arbBook.buyTree[buyer].order.Price { 80 | fundsLeft[buyerExchange][xgen.BTC] = 0 81 | } 82 | // If not enough USD in the account for the minimum allowed trade size (buy), it's the same as if the account was empty of USD 83 | if fundsLeft[sellerExchange][xgen.USD] < minTrade[sellerExchange][xgen.USD] || 84 | fundsLeft[sellerExchange][xgen.USD] < minTrade[sellerExchange][xgen.BTC]*arbBook.sellTree[seller].order.Price { 85 | fundsLeft[sellerExchange][xgen.USD] = 0 86 | } 87 | 88 | // Arbitrage found -> update the execution plan as long as funds still left 89 | if fundsLeft[buyerExchange][xgen.BTC] > 0 { 90 | arb.Sell[buyerExchange].Price = arbBook.buyTree[buyer].order.Price 91 | } 92 | if fundsLeft[sellerExchange][xgen.USD] > 0 { 93 | arb.Buy[sellerExchange].Price = arbBook.sellTree[seller].order.Price 94 | } 95 | 96 | // Can't make a bigger trades than we have funds for 97 | if buyerAmount > fundsLeft[buyerExchange][xgen.BTC] { 98 | buyerAmount = fundsLeft[buyerExchange][xgen.BTC] 99 | } 100 | if sellerAmount*arbBook.sellTree[seller].order.Price > fundsLeft[sellerExchange][xgen.USD] { 101 | sellerAmount = fundsLeft[sellerExchange][xgen.USD] / arbBook.sellTree[seller].order.Price 102 | } 103 | 104 | // Available arbitrage is limited to the volume of the smaller side (buyer/seller). 105 | // For the sake of simplicity, we keep the (absolute) amount of BTC same after the trade as it was before the trade (i.e. all the profit will be in USD), 106 | // (even though theoretically a more correct way might be to keep the relative balances the same for all currencies). 107 | switch { 108 | case buyerAmount > sellerAmount*(1-commission[buyerExchange]): 109 | buyerCapped := sellerAmount * (1 - commission[buyerExchange]) 110 | arb.Sell[buyerExchange].Amount += buyerCapped 111 | arb.Buy[sellerExchange].Amount += sellerAmount 112 | fundsLeft[buyerExchange][xgen.BTC] -= buyerCapped 113 | fundsLeft[sellerExchange][xgen.USD] -= sellerAmount * arb.Buy[sellerExchange].Price 114 | buyerAmount -= buyerCapped 115 | seller++ 116 | if seller == len(arbBook.sellTree) { 117 | return 118 | } 119 | sellerAmount = arbBook.sellTree[seller].order.Amount 120 | case buyerAmount < sellerAmount*(1-commission[buyerExchange]): 121 | sellerCapped := buyerAmount / (1 - commission[buyerExchange]) 122 | arb.Sell[buyerExchange].Amount += buyerAmount 123 | arb.Buy[sellerExchange].Amount += sellerCapped 124 | fundsLeft[buyerExchange][xgen.BTC] -= buyerAmount 125 | fundsLeft[sellerExchange][xgen.USD] -= sellerCapped * arb.Buy[sellerExchange].Price 126 | sellerAmount -= sellerCapped 127 | buyer++ 128 | if buyer == len(arbBook.buyTree) { 129 | return 130 | } 131 | buyerAmount = arbBook.buyTree[buyer].order.Amount 132 | default: 133 | arb.Sell[buyerExchange].Amount += buyerAmount 134 | arb.Buy[sellerExchange].Amount += sellerAmount 135 | fundsLeft[buyerExchange][xgen.BTC] -= buyerAmount 136 | fundsLeft[sellerExchange][xgen.USD] -= sellerAmount * arb.Buy[sellerExchange].Price 137 | buyer++ 138 | seller++ 139 | if buyer == len(arbBook.buyTree) || seller == len(arbBook.sellTree) { 140 | return 141 | } 142 | buyerAmount = arbBook.buyTree[buyer].order.Amount 143 | sellerAmount = arbBook.sellTree[seller].order.Amount 144 | } 145 | buyerExchange = arbBook.buyTree[buyer].exchange 146 | sellerExchange = arbBook.sellTree[seller].exchange 147 | } 148 | return 149 | } 150 | 151 | // Onesided adjusts the amounts in an existing strategy to balance the USD and BTC amounts within each exchange. 152 | func Onesided(strategy Strategy, funds []xgen.Balance, commission []float64) (newStgy Strategy) { 153 | newStgy.Buy = make([]xgen.Order, len(strategy.Buy)) 154 | newStgy.Sell = make([]xgen.Order, len(strategy.Sell)) 155 | copy(newStgy.Buy, strategy.Buy) 156 | copy(newStgy.Sell, strategy.Sell) 157 | 158 | for i := 0; i < len(funds); i++ { 159 | usdLeft := funds[i][xgen.USD] + strategy.Sell[i].Amount*strategy.Sell[i].Price*(1-commission[i]) - strategy.Buy[i].Amount*strategy.Buy[i].Price 160 | btcLeft := funds[i][xgen.BTC] + strategy.Buy[i].Amount*(1-commission[i]) - strategy.Sell[i].Amount 161 | if strategy.Buy[i].Price > 0 && usdLeft > btcLeft*strategy.Buy[i].Price { 162 | newStgy.Buy[i].Amount = strategy.Buy[i].Amount + (usdLeft/strategy.Buy[i].Price-btcLeft)/(2-commission[i]) 163 | } 164 | if strategy.Sell[i].Price > 0 && btcLeft*strategy.Sell[i].Price > usdLeft { 165 | newStgy.Sell[i].Amount = strategy.Sell[i].Amount + (btcLeft-usdLeft/strategy.Sell[i].Price)/(2-commission[i]) 166 | } 167 | } 168 | return 169 | } 170 | -------------------------------------------------------------------------------- /arbitrage/arbitragetest.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | package arbitrage 5 | 6 | // TODO: Unit tests need to be written using "gotest" (and file renamed to arbitrage_test.go). 7 | 8 | import ( 9 | "xgen" 10 | // "testing" 11 | "os" 12 | "fmt" 13 | ) 14 | 15 | type arbTest struct { 16 | book []xgen.OrderBook 17 | funds []xgen.Balance 18 | commission []float64 19 | minTrade [][xgen.NumCurrencies]float64 20 | out Strategy 21 | } 22 | 23 | type onesidedTest struct { 24 | funds []xgen.Balance 25 | commission []float64 26 | in Strategy 27 | out Strategy 28 | } 29 | 30 | var arbTests = []arbTest{ 31 | // Test #1: Arbitrage between 2 exchanges with 20% commissions: After commissions we would pay $7.50 to get 1.5 BTC, and sell 1.5 BTC for $8.40. 32 | arbTest{ 33 | []xgen.OrderBook{ 34 | {BuyTree: []xgen.Order{{8.0, 1.0}, {7.0, 2.0}}, SellTree: []xgen.Order{{9.0, 10.0}}}, // Price, Amount 35 | {BuyTree: []xgen.Order{{1.0, 10.0}}, SellTree: []xgen.Order{{4.0, 2.0}}}, 36 | }, 37 | []xgen.Balance{ 38 | [xgen.NumCurrencies]float64{1.5, 10.0}, // BTC, USD 39 | [xgen.NumCurrencies]float64{10.0, 10.0}, 40 | }, 41 | []float64{0.2, 0.2}, // commissions 42 | [][xgen.NumCurrencies]float64{{0, 0}, {0, 0}}, // minimum allowed trade amounts 43 | Strategy{Buy: []xgen.Order{{0, 0}, {4.0, 1.875}}, Sell: []xgen.Order{{7.0, 1.5}, {0, 0}}}, 44 | }, 45 | // Test #2: 3-way arbitrage with no commissions (for simplicity). 46 | arbTest{ 47 | []xgen.OrderBook{ 48 | {BuyTree: []xgen.Order{{6.5, 1.0}, {5.5, 2.0}, {4.5, 4.0}}, SellTree: []xgen.Order{{10.0, 100.0}}}, // Price, Amount 49 | {BuyTree: []xgen.Order{{1.0, 100.0}}, SellTree: []xgen.Order{{4.5, 1.0}, {5.5, 2.0}, {6.5, 4.0}}}, 50 | {BuyTree: []xgen.Order{{4.9, 2.0}, {4.8, 4.0}, {4.7, 8.0}}, SellTree: []xgen.Order{{5.0, 2.0}, {5.1, 4.0}, {5.2, 8.0}}}, 51 | }, 52 | []xgen.Balance{ 53 | [xgen.NumCurrencies]float64{2.0, 0.0}, // BTC, USD 54 | [xgen.NumCurrencies]float64{0.0, 20.0}, 55 | [xgen.NumCurrencies]float64{0.5, 10.0}, 56 | }, 57 | []float64{0.0, 0.0, 0.0}, // commissions 58 | [][xgen.NumCurrencies]float64{{0, 0}, {0, 0}, {0, 0}}, // minimum allowed trade amounts 59 | Strategy{Buy: []xgen.Order{{0, 0}, {4.5, 1.0}, {5.0, 1.0}}, Sell: []xgen.Order{{5.5, 2.0}, {0, 0}, {0, 0}}}, 60 | }, 61 | // Test #3: Same as test #2 but adjusted account balances enough to change to output 62 | arbTest{ 63 | []xgen.OrderBook{ 64 | {BuyTree: []xgen.Order{{6.5, 1.0}, {5.5, 2.0}, {4.5, 4.0}}, SellTree: []xgen.Order{{10.0, 100.0}}}, // Price, Amount 65 | {BuyTree: []xgen.Order{{1.0, 100.0}}, SellTree: []xgen.Order{{4.5, 1.0}, {5.5, 2.0}, {6.5, 4.0}}}, 66 | {BuyTree: []xgen.Order{{4.9, 2.0}, {4.8, 4.0}, {4.7, 8.0}}, SellTree: []xgen.Order{{5.0, 2.0}, {5.1, 4.0}, {5.2, 8.0}}}, 67 | }, 68 | []xgen.Balance{ 69 | [xgen.NumCurrencies]float64{2.0, 0.0}, // BTC, USD 70 | [xgen.NumCurrencies]float64{0.0, 20.0}, 71 | [xgen.NumCurrencies]float64{0.5, 2.5}, 72 | }, 73 | []float64{0.0, 0.0, 0.0}, // commissions 74 | [][xgen.NumCurrencies]float64{{0, 0}, {0, 0}, {0, 0}}, // minimum allowed trade amounts 75 | Strategy{Buy: []xgen.Order{{0, 0}, {4.5, 1.0}, {5.0, 0.5}}, Sell: []xgen.Order{{5.5, 1.5}, {0, 0}, {0, 0}}}, 76 | }, 77 | } 78 | 79 | var onesidedTests = []onesidedTest{ 80 | onesidedTest{ 81 | []xgen.Balance{ 82 | [xgen.NumCurrencies]float64{2.0, 0.0}, // BTC, USD 83 | [xgen.NumCurrencies]float64{1.0, 20.0}, 84 | [xgen.NumCurrencies]float64{1.0, 2.0}, 85 | }, 86 | []float64{0.4, 0.4, 0.4}, // commissions 87 | Strategy{Buy: []xgen.Order{{0, 0}, {4.0, 1.0}, {4.0, 0.5}}, Sell: []xgen.Order{{6.0, 0.50}, {0, 0}, {0, 0}}}, 88 | Strategy{Buy: []xgen.Order{{0, 0}, {4.0, 2.5}, {4.0, 0.5}}, Sell: []xgen.Order{{6.0, 1.25}, {0, 0}, {0, 0}}}, 89 | }, 90 | } 91 | 92 | func TestCalculate( /*t *testing.T*/ ) os.Error { 93 | for i, at := range arbTests { 94 | v := Calculate(at.book, at.funds, at.commission, at.minTrade) 95 | if fmt.Sprint(v) != fmt.Sprint(at.out) { 96 | //t.Errorf("arbitrageStrategy = %d, want %d.", v, at.out) 97 | return os.NewError(fmt.Sprint("ArbitrageStrategy (#", (i + 1), ")
", at.book, "
", at.funds, "
=
", v, "
want
", at.out)) 98 | } 99 | } 100 | return nil 101 | } 102 | 103 | func TestOnesided( /*t *testing.T*/ ) os.Error { 104 | for i, ot := range onesidedTests { 105 | v := Onesided(ot.in, ot.funds, ot.commission) 106 | if fmt.Sprint(v) != fmt.Sprint(ot.out) { 107 | //t.Errorf("onesidedArbitrage = %d, want %d.", v, ot.out) 108 | return os.NewError(fmt.Sprint("OnesidedArbitrage (#", (i + 1), ")
", ot.in, "
=
", v, "
want
", ot.out)) 109 | } 110 | } 111 | return nil 112 | } 113 | -------------------------------------------------------------------------------- /campbx/campbx.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package campbx implements functions for sending and receiving data via CampBX API. 5 | package campbx 6 | 7 | // CampBX API: https://campbx.com/api.php 8 | const ( 9 | // Public Market Data 10 | JsonTicker = "http://campbx.com/api/xticker.php" 11 | JsonDepth = "http://CampBX.com/api/xdepth.php" 12 | 13 | // Authenticated Trading Functions 14 | JsonBalance = "https://CampBX.com/api/myfunds.php" 15 | JsonOrders = "https://CampBX.com/api/myorders.php" 16 | JsonBuySell = "https://CampBX.com/api/tradeenter.php" 17 | JsonCancel = "https://CampBX.com/api/tradecancel.php" 18 | ) 19 | 20 | // Quote is a struct representing the best available buy and sell prices at the time. 21 | type Quote struct { 22 | Buy string `json:"Best Bid"` 23 | Sell string `json:"Best Ask"` 24 | Last string `json:"Last Trade"` 25 | } 26 | 27 | // OrderBook is a struct representing a limit order book. 28 | type OrderBook struct { 29 | Asks [][2]float64 // Sell orders (price and amount) 30 | Bids [][2]float64 // Buy orders (price and amount) 31 | } 32 | 33 | const ( 34 | Price = iota 35 | Amount 36 | ) 37 | 38 | // Balance contains the amount of each currency in the account. 39 | type Balance struct { 40 | UsdTotal string `json:"Total USD"` 41 | UsdLiquid string `json:"Liquid USD"` 42 | UsdMargin string `json:"Margin Account USD"` 43 | BtcTotal string `json:"Total BTC"` 44 | BtcLiquid string `json:"Liquid BTC"` 45 | BtcMargin string `json:"Margin Account BTC"` 46 | } 47 | 48 | type openOrder struct { 49 | Info string // Optional, e.g. "No open Buy Orders" 50 | OrderType string `json:"Order Type"` // e.g. "Quick Sell" 51 | Oid string `json:"Order ID"` // Unique order id 52 | Price string // Price of BTC in USD 53 | Quantity string // Amount of BTC 54 | MarginPct string `json:"Margin Percent"` 55 | StopLoss string `json:"Stop-loss"` 56 | FillType string `json:"Fill Type"` 57 | DarkPool string `json:"Dark Pool"` 58 | DateEntered string `json:"Order Entered"` 59 | DateExpires string `json:"Order Expiry"` 60 | } 61 | 62 | // OpenOrders is a struct representing all our open buy and sell orders in the account. 63 | type OpenOrders struct { 64 | Buy []openOrder 65 | Sell []openOrder 66 | } 67 | -------------------------------------------------------------------------------- /campbx/campbxapi.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | package campbx 5 | 6 | import ( 7 | "appengine" 8 | "os" 9 | "restapi" 10 | "xgen" 11 | "strconv" 12 | "sort" 13 | "appengine/datastore" 14 | "time" 15 | ) 16 | 17 | func check(err os.Error) { 18 | if err != nil { 19 | panic(err) 20 | } 21 | } 22 | 23 | // GetQuote retrieves the "ticker" data. 24 | func GetQuote(c appengine.Context) (x xgen.Quote, err os.Error) { 25 | defer func() { 26 | if e, ok := recover().(os.Error); ok { 27 | err = e 28 | } 29 | }() 30 | var q Quote 31 | err = restapi.GetJson(c, JsonTicker, &q) 32 | check(err) 33 | x.Date = datastore.SecondsToTime(time.Seconds()) 34 | x.HighestBuy, err = strconv.Atof64(q.Buy) 35 | check(err) 36 | x.LowestSell, err = strconv.Atof64(q.Sell) 37 | check(err) 38 | x.Last, err = strconv.Atof64(q.Last) 39 | check(err) 40 | if !x.Validate() { 41 | panic("Invalid Ticker") 42 | } 43 | return 44 | } 45 | 46 | // GetOrderBook retrieves the limit order book. 47 | func GetOrderBook(c appengine.Context) (x xgen.OrderBook, err os.Error) { 48 | defer func() { 49 | if e, ok := recover().(os.Error); ok { 50 | err = e 51 | } 52 | }() 53 | var b OrderBook 54 | err = restapi.GetJson(c, JsonDepth, &b) 55 | check(err) 56 | for _, ask := range b.Asks { 57 | o := xgen.Order{Price: ask[Price], Amount: ask[Amount]} 58 | x.SellTree = append(x.SellTree, o) 59 | } 60 | for _, bid := range b.Bids { 61 | o := xgen.Order{Price: bid[Price], Amount: bid[Amount]} 62 | x.BuyTree = append(x.BuyTree, o) 63 | } 64 | if !x.Validate() { 65 | panic("Invalid Depth") 66 | } 67 | sort.Sort(x.BuyTree) 68 | sort.Sort(x.SellTree) 69 | x.BuyTree.Reverse() 70 | return 71 | } 72 | 73 | // GetBalance retrieves the account balance. 74 | func GetBalance(c appengine.Context, login xgen.Credentials) (x xgen.Balance, err os.Error) { 75 | defer func() { 76 | if e, ok := recover().(os.Error); ok { 77 | err = e 78 | } 79 | }() 80 | var b Balance 81 | err = restapi.PostJson(c, JsonBalance, map[string][]string{"user": {login.Username}, "pass": {login.Password}}, &b) 82 | check(err) 83 | x[xgen.BTC], err = strconv.Atof64(b.BtcLiquid) 84 | check(err) 85 | x[xgen.USD], err = strconv.Atof64(b.UsdLiquid) 86 | return 87 | } 88 | 89 | func (h OpenOrders) convert() (o xgen.OpenOrders) { // Convert campbx.OpenOrders to xgen.OpenOrders 90 | var err os.Error 91 | o.Sell = make(map[string]xgen.OpenOrder) 92 | o.Buy = make(map[string]xgen.OpenOrder) 93 | for _, order := range h.Buy { 94 | if order.Oid != "" { 95 | var t xgen.OpenOrder 96 | t.Date = time.Seconds() // Should use time.Parse to convert order.DateEntered to Unix time 97 | t.Price, err = strconv.Atof64(order.Price) 98 | check(err) 99 | t.Amount, err = strconv.Atof64(order.Quantity) 100 | check(err) 101 | o.Buy[order.Oid] = t 102 | } 103 | } 104 | for _, order := range h.Sell { 105 | if order.Oid != "" { 106 | var t xgen.OpenOrder 107 | t.Date = time.Seconds() // Should use time.Parse to convert order.DateEntered to Unix time 108 | t.Price, err = strconv.Atof64(order.Price) 109 | check(err) 110 | t.Amount, err = strconv.Atof64(order.Quantity) 111 | check(err) 112 | o.Sell[order.Oid] = t 113 | } 114 | } 115 | return 116 | } 117 | 118 | // GetOpenOrders retrieves a list of all open orders. 119 | func GetOpenOrders(c appengine.Context, login xgen.Credentials) (x xgen.OpenOrders, err os.Error) { 120 | defer func() { 121 | if e, ok := recover().(os.Error); ok { 122 | err = e 123 | } 124 | }() 125 | var openOrders OpenOrders 126 | err = restapi.PostJson(c, JsonOrders, map[string][]string{"user": {login.Username}, "pass": {login.Password}}, &openOrders) 127 | check(err) 128 | x = openOrders.convert() 129 | return 130 | } 131 | 132 | // CancelOrder cancels an open order. 133 | func CancelOrder(c appengine.Context, login xgen.Credentials, oid string, orderType string) (f interface{}, err os.Error) { 134 | err = restapi.PostJson(c, JsonCancel, map[string][]string{"user": {login.Username}, "pass": {login.Password}, "Type": {orderType}, "OrderID": {oid}}, &f) 135 | return 136 | } 137 | 138 | // Buy opens a new order to buy BTC. 139 | func Buy(c appengine.Context, login xgen.Credentials, price float64, amount float64) (f interface{}, err os.Error) { 140 | err = restapi.PostJson(c, JsonBuySell, map[string][]string{"user": {login.Username}, "pass": {login.Password}, "TradeMode": {"QuickBuy"}, 141 | "Price": {strconv.Ftoa64(price, 'f', -1)}, "Quantity": {strconv.Ftoa64(amount, 'f', -1)}}, &f) 142 | return 143 | } 144 | 145 | // Sell opens a new order to sell BTC. 146 | func Sell(c appengine.Context, login xgen.Credentials, price float64, amount float64) (f interface{}, err os.Error) { 147 | err = restapi.PostJson(c, JsonBuySell, map[string][]string{"user": {login.Username}, "pass": {login.Password}, "TradeMode": {"QuickSell"}, 148 | "Price": {strconv.Ftoa64(price, 'f', -1)}, "Quantity": {strconv.Ftoa64(amount, 'f', -1)}}, &f) 149 | return 150 | } 151 | -------------------------------------------------------------------------------- /cron.yaml: -------------------------------------------------------------------------------- 1 | cron: 2 | - description: check for arbitrage once per minute 3 | url: /cron/ 4 | schedule: every 1 minutes 5 | -------------------------------------------------------------------------------- /mtgox/mtgox.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package mtgox implements functions for sending and receiving data via Mt Gox API. 5 | package mtgox 6 | 7 | // Mt. Gox Trade API: https://mtgox.com/support/tradeAPI 8 | // API documentation: https://en.bitcoin.it/wiki/MtGox/API 9 | const ( 10 | // Public Market Data 11 | JsonTicker = "https://mtgox.com/api/0/data/ticker.php" 12 | JsonDepth = "https://mtgox.com/api/0/data/getDepth.php" 13 | JsonRecent = "https://mtgox.com/api/0/data/getTrades.php" 14 | 15 | // Authenticated Trading Functions 16 | JsonBalance = "https://mtgox.com/api/0/getFunds.php" 17 | JsonOrders = "https://mtgox.com/api/0/getOrders.php" 18 | JsonBuy = "https://mtgox.com/api/0/buyBTC.php" 19 | JsonSell = "https://mtgox.com/api/0/sellBTC.php" 20 | JsonCancel = "https://mtgox.com/api/0/cancelOrder.php" 21 | ) 22 | 23 | type quote struct { 24 | Buy float64 // Highest Bid 25 | Sell float64 // Lowest Ask 26 | Vol int64 // Traded volume since last close 27 | High float64 // Maximum rate (?) since last close 28 | Low float64 // Minimum rate (?) since last close 29 | Last float64 30 | Avg float64 31 | Vwap float64 32 | } 33 | 34 | // Quote is a struct representing the best available buy and sell prices at the time. 35 | type Quote struct { 36 | Ticker quote 37 | } 38 | 39 | // OrderBook is a struct representing a limit order book. 40 | type OrderBook struct { 41 | Asks [][2]float64 // Sell orders (price and amount) 42 | Bids [][2]float64 // Buy orders (price and amount) 43 | } 44 | 45 | const ( 46 | Price = iota 47 | Amount 48 | ) 49 | 50 | // Trade is a struct representing a historical trade. 51 | type Trade struct { 52 | Date int64 // Unix timestamp of the trade 53 | Tid string // Trade id (big integer, which is in fact the trade timestamp in microseconds) 54 | Price_int string // Price per unit * 1E5 or 1E3 (1E5 for USD, 1E3 for JPY) 55 | // USD: multiply by 0.00001 to get the actual price of BTC in USD, JPY: multiply by 0.001 56 | Amount_int string // Traded amount * 1E8 (multiply by 0.00000001 to get the actual number of BTC traded) 57 | Price_currency string // Currency in which trade was completed (USD? JPY?) 58 | Item string // What was this trade about (BTC?) 59 | Trade_type string // Did this trade result from the execution of a 'bid' or 'ask'? 60 | 61 | // Old API values with float types - deprecated 62 | // Price string 63 | // Amount string 64 | } 65 | 66 | // RecentTrades is a struct representing a slice of historical trades. 67 | type RecentTrades struct { 68 | Trades []Trade 69 | } 70 | 71 | // Balance contains the amount of each currency in the account. 72 | type Balance struct { 73 | Usds string 74 | Btcs string 75 | } 76 | 77 | type newBalance struct { 78 | Currency string // USD / BTC 79 | Value string // Float 80 | Value_int string // Int *1E5 or *1E8 ? 81 | Display string // String format including the currency symbol (e.g. "$") 82 | } 83 | 84 | type openOrder struct { 85 | OrderType int8 `json:"type"` // 1 = Sell order, 2 = Buy order 86 | Status int8 // 1 = Active 87 | Real_status string // "open" or ? 88 | Oid string // Unique order id (but not int, e.g. "2d8dfdd1-5342-42bc-9dde-a81fdfa63920") 89 | Currency string // ? Was "USD" when trying to buy BTC with USD 90 | Item string // ? Was "BTC" when trying to buy BTC 91 | Price string // Price of BTC in USD ? 92 | Price_int string // Price of BTC in USD ? times 1E5 93 | Amount string // Amount of BTC ? 94 | Amount_int string // Amount of BTC ? times 1E8 95 | Dark int8 // Dark Pool ? 96 | Priority string // ? int 97 | Date int64 98 | } 99 | 100 | // OpenOrders is a struct representing all our open buy and sell orders in the account. 101 | type OpenOrders struct { 102 | Usds string 103 | Btcs string 104 | New_Usds newBalance 105 | New_btcs newBalance 106 | Orders []openOrder 107 | } 108 | -------------------------------------------------------------------------------- /mtgox/mtgoxapi.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // TODO: Add HTTP headers, though it works fine without the headers too (at least for now) 5 | 6 | package mtgox 7 | 8 | import ( 9 | "appengine" 10 | "os" 11 | "restapi" 12 | "xgen" 13 | "strconv" 14 | "sort" 15 | "appengine/datastore" 16 | "time" 17 | ) 18 | 19 | func check(err os.Error) { 20 | if err != nil { 21 | panic(err) 22 | } 23 | } 24 | 25 | // GetQuote retrieves the "ticker" data. 26 | func GetQuote(c appengine.Context) (x xgen.Quote, err os.Error) { 27 | defer func() { 28 | if e, ok := recover().(os.Error); ok { 29 | err = e 30 | } 31 | }() 32 | var q Quote 33 | err = restapi.GetJson(c, JsonTicker, &q) 34 | check(err) 35 | x.Date = datastore.SecondsToTime(time.Seconds()) 36 | x.HighestBuy = q.Ticker.Buy 37 | x.LowestSell = q.Ticker.Sell 38 | x.Last = q.Ticker.Last 39 | if !x.Validate() { 40 | panic("Invalid Ticker") 41 | } 42 | return 43 | } 44 | 45 | // GetOrderBook retrieves the limit order book. 46 | func GetOrderBook(c appengine.Context) (x xgen.OrderBook, err os.Error) { 47 | defer func() { 48 | if e, ok := recover().(os.Error); ok { 49 | err = e 50 | } 51 | }() 52 | var b OrderBook 53 | err = restapi.GetJson(c, JsonDepth, &b) 54 | check(err) 55 | for _, ask := range b.Asks { 56 | o := xgen.Order{Price: ask[Price], Amount: ask[Amount]} 57 | x.SellTree = append(x.SellTree, o) 58 | } 59 | for _, bid := range b.Bids { 60 | o := xgen.Order{Price: bid[Price], Amount: bid[Amount]} 61 | x.BuyTree = append(x.BuyTree, o) 62 | } 63 | if !x.Validate() { 64 | panic("Invalid Depth") 65 | } 66 | sort.Sort(x.BuyTree) 67 | sort.Sort(x.SellTree) 68 | x.BuyTree.Reverse() 69 | return 70 | } 71 | 72 | // GetBalance retrieves the account balance. 73 | func GetBalance(c appengine.Context, login xgen.Credentials) (x xgen.Balance, err os.Error) { 74 | defer func() { 75 | if e, ok := recover().(os.Error); ok { 76 | err = e 77 | } 78 | }() 79 | var b Balance 80 | err = restapi.PostJson(c, JsonBalance, map[string][]string{"name": {login.Username}, "pass": {login.Password}, "nonce": {strconv.Itoa64(time.Nanoseconds())}}, &b) 81 | check(err) 82 | x[xgen.BTC], err = strconv.Atof64(b.Btcs) 83 | check(err) 84 | x[xgen.USD], err = strconv.Atof64(b.Usds) 85 | check(err) 86 | return 87 | } 88 | 89 | func (h OpenOrders) convert() (o xgen.OpenOrders) { // Convert mtgox.OpenOrders to xgen.OpenOrders 90 | var err os.Error 91 | o.Sell = make(map[string]xgen.OpenOrder) 92 | o.Buy = make(map[string]xgen.OpenOrder) 93 | for _, order := range h.Orders { 94 | var t xgen.OpenOrder 95 | t.Date = order.Date 96 | t.Price, err = strconv.Atof64(order.Price) 97 | check(err) 98 | t.Amount, err = strconv.Atof64(order.Amount) 99 | check(err) 100 | if order.OrderType == 1 { // Sell order 101 | o.Sell[order.Oid] = t 102 | } else if order.OrderType == 2 { // Buy order 103 | o.Buy[order.Oid] = t 104 | } else { 105 | panic("Invalid order type") 106 | } 107 | } 108 | return 109 | } 110 | 111 | // GetOpenOrders retrieves a list of all open orders. 112 | func GetOpenOrders(c appengine.Context, login xgen.Credentials) (x xgen.OpenOrders, err os.Error) { 113 | defer func() { 114 | if e, ok := recover().(os.Error); ok { 115 | err = e 116 | } 117 | }() 118 | var openOrders OpenOrders 119 | err = restapi.PostJson(c, JsonOrders, map[string][]string{"name": {login.Username}, "pass": {login.Password}, "nonce": {strconv.Itoa64(time.Nanoseconds())}}, &openOrders) 120 | check(err) 121 | x = openOrders.convert() 122 | return 123 | } 124 | 125 | // CancelOrder cancels an open order. 126 | func CancelOrder(c appengine.Context, login xgen.Credentials, oid string, orderType int8) (f interface{}, err os.Error) { 127 | err = restapi.PostJson(c, JsonCancel, map[string][]string{"name": {login.Username}, "pass": {login.Password}, "nonce": {strconv.Itoa64(time.Nanoseconds())}, 128 | "oid": {oid}, "type": {strconv.Itoa(int(orderType))}}, &f) 129 | return 130 | } 131 | 132 | // Buy opens a new order to buy BTC. 133 | func Buy(c appengine.Context, login xgen.Credentials, price float64, amount float64) (x xgen.OpenOrders, err os.Error) { 134 | defer func() { 135 | if e, ok := recover().(os.Error); ok { 136 | err = e 137 | } 138 | }() 139 | var openOrders OpenOrders 140 | err = restapi.PostJson(c, JsonBuy, map[string][]string{"name": {login.Username}, "pass": {login.Password}, "nonce": {strconv.Itoa64(time.Nanoseconds())}, 141 | "price": {strconv.Ftoa64(price, 'f', -1)}, "amount": {strconv.Ftoa64(amount, 'f', -1)}}, &openOrders) 142 | check(err) 143 | x = openOrders.convert() 144 | return 145 | } 146 | 147 | // Sell opens a new order to sell BTC. 148 | func Sell(c appengine.Context, login xgen.Credentials, price float64, amount float64) (x xgen.OpenOrders, err os.Error) { 149 | defer func() { 150 | if e, ok := recover().(os.Error); ok { 151 | err = e 152 | } 153 | }() 154 | var openOrders OpenOrders 155 | err = restapi.PostJson(c, JsonSell, map[string][]string{"name": {login.Username}, "pass": {login.Password}, "nonce": {strconv.Itoa64(time.Nanoseconds())}, 156 | "price": {strconv.Ftoa64(price, 'f', -1)}, "amount": {strconv.Ftoa64(amount, 'f', -1)}}, &openOrders) 157 | check(err) 158 | x = openOrders.convert() 159 | return 160 | } 161 | -------------------------------------------------------------------------------- /restapi/restapi.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package restapi implements basic functions to be used with RESTful API's returning JSON responses. 5 | package restapi 6 | 7 | import ( 8 | "appengine" 9 | "appengine/urlfetch" 10 | "os" 11 | "io/ioutil" 12 | "json" 13 | "http" 14 | ) 15 | 16 | // GetJson fetches a URL using a GET request, parses the returned JSON response, and stores the response in struct |a|. 17 | func GetJson(c appengine.Context, url string, a interface{}) (err os.Error) { 18 | defer func() { 19 | if e, ok := recover().(os.Error); ok { 20 | err = e 21 | } 22 | }() 23 | b := getUrl(c, url) 24 | err = json.Unmarshal(b, &a) 25 | return 26 | } 27 | 28 | // PostJson submits data to a URL using a POST request, parses the returned JSON response, and stores the response in struct |a|. 29 | func PostJson(c appengine.Context, url string, data map[string][]string, a interface{}) (err os.Error) { 30 | defer func() { 31 | if e, ok := recover().(os.Error); ok { 32 | err = e 33 | } 34 | }() 35 | b := postForm(c, url, data) 36 | err = json.Unmarshal(b, &a) 37 | return 38 | } 39 | 40 | func check(err os.Error) { 41 | if err != nil { 42 | panic(err) 43 | } 44 | } 45 | 46 | func getUrl(c appengine.Context, url string) []byte { 47 | /*client := urlfetch.Client(c) 48 | res, err := client.Get(url) 49 | check(err)*/ 50 | req, err := http.NewRequest("GET", url, nil) 51 | check(err) 52 | t := &urlfetch.Transport{c, 10, true} // Set timeout to 10 seconds (instead of the default 5) 53 | res, err := t.RoundTrip(req) 54 | check(err) 55 | defer res.Body.Close() 56 | b, err := ioutil.ReadAll(res.Body) 57 | check(err) 58 | return b 59 | } 60 | 61 | func postForm(c appengine.Context, url string, data map[string][]string) []byte { 62 | client := urlfetch.Client(c) 63 | res, err := client.PostForm(url, data) 64 | check(err) 65 | defer res.Body.Close() 66 | b, err := ioutil.ReadAll(res.Body) 67 | check(err) 68 | return b 69 | } 70 | -------------------------------------------------------------------------------- /tradehill/tradehill.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package tradehill implements functions for sending and receiving data via TradeHill API. 5 | package tradehill 6 | 7 | // TradeHill Trading API: https://www.tradehill.com/Support/TradingAPI/ 8 | // Description of the data: http://bitcoincharts.com/about/exchanges/ 9 | const ( 10 | // Public Market Data 11 | JsonTicker = "https://api.tradehill.com/APIv1/USD/Ticker" 12 | JsonDepth = "https://api.tradehill.com/APIv1/USD/Orderbook" 13 | JsonRecent = "https://api.tradehill.com/APIv1/USD/Trades" 14 | 15 | // Authenticated Trading Functions 16 | JsonBalance = "https://api.tradehill.com/APIv1/USD/GetBalance" 17 | JsonOrders = "https://api.tradehill.com/APIv1/USD/GetOrders" 18 | JsonBuy = "https://api.tradehill.com/APIv1/USD/BuyBTC" 19 | JsonSell = "https://api.tradehill.com/APIv1/USD/SellBTC" 20 | JsonCancel = "https://api.tradehill.com/APIv1/USD/CancelOrder" 21 | ) 22 | 23 | type quote struct { 24 | Buy string 25 | Sell string 26 | Last string 27 | Vol string 28 | High string 29 | Low string 30 | Last_when string // E.g. "5 minutes ago" 31 | } 32 | 33 | // Quote is a struct representing the best available buy and sell prices at the time. 34 | type Quote struct { 35 | Ticker quote 36 | } 37 | 38 | // OrderBook is a struct representing a limit order book. 39 | type OrderBook struct { 40 | Asks [][2]string // Sell orders (price and amount) 41 | Bids [][2]string // Buy orders (price and amount) 42 | } 43 | 44 | const ( 45 | Price = iota 46 | Amount 47 | ) 48 | 49 | // Trade is a struct representing a historical trade. 50 | type Trade struct { 51 | Date int64 // Unix timestamp of the trade 52 | Tid int64 // Unique trade id (monotonically increasing integer) for each trade 53 | Price string // Price in your markets currency (e.g. USD) 54 | Amount string // Amount of bitcoins exchanged in that trade 55 | } 56 | 57 | // RecentTrades is a struct representing a slice of historical trades. 58 | type RecentTrades struct { 59 | Trades []Trade 60 | } 61 | 62 | // Balance contains the amount of each currency in the account. 63 | type Balance struct { 64 | USD string // Can be "0E-10" ? 65 | USD_Available string 66 | USD_Reserved string 67 | BTC string 68 | BTC_Available string 69 | BTC_Reserved string 70 | } 71 | 72 | type openOrder struct { 73 | OrderType int8 `json:"type"` // 1 = Sell order, 2 = Buy order 74 | Status int8 // 1 = Active (which is the value for all returned order, any other value here indicates an error) 75 | Oid int64 // Unique order id 76 | Symbol string // Currency symbol (currently always "BTC") 77 | Price string // Limit price of the order (in USD) 78 | Amount_orig string // The original amount (size) of your order 79 | Amount string // The amount (size) of your order that remains to be filled (amount = amount_orig - amount filled) 80 | Reserved_amount string // The amount of money reserved in order to fill this order (includes estimated commissions) 81 | Reserved_currency string // The currency of the reserved money (USD for buy orders, BTC for sell orders) 82 | Date int64 // The datetime this order was created 83 | } 84 | 85 | // OpenOrders is a struct representing all our open buy and sell orders in the account. 86 | type OpenOrders struct { 87 | Orders []openOrder 88 | } 89 | -------------------------------------------------------------------------------- /tradehill/tradehillapi.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | package tradehill 5 | 6 | import ( 7 | "appengine" 8 | "os" 9 | "restapi" 10 | "xgen" 11 | "strconv" 12 | "sort" 13 | "appengine/datastore" 14 | "time" 15 | ) 16 | 17 | func check(err os.Error) { 18 | if err != nil { 19 | panic(err) 20 | } 21 | } 22 | 23 | // GetQuote retrieves the "ticker" data. 24 | func GetQuote(c appengine.Context) (x xgen.Quote, err os.Error) { 25 | defer func() { 26 | if e, ok := recover().(os.Error); ok { 27 | err = e 28 | } 29 | }() 30 | var q Quote 31 | err = restapi.GetJson(c, JsonTicker, &q) 32 | check(err) 33 | x.Date = datastore.SecondsToTime(time.Seconds()) 34 | x.HighestBuy, err = strconv.Atof64(q.Ticker.Buy) 35 | check(err) 36 | x.LowestSell, err = strconv.Atof64(q.Ticker.Sell) 37 | check(err) 38 | x.Last, err = strconv.Atof64(q.Ticker.Last) 39 | check(err) 40 | if !x.Validate() { 41 | panic("Invalid Ticker") 42 | } 43 | return 44 | } 45 | 46 | // GetOrderBook retrieves the limit order book. 47 | func GetOrderBook(c appengine.Context) (x xgen.OrderBook, err os.Error) { 48 | defer func() { 49 | if e, ok := recover().(os.Error); ok { 50 | err = e 51 | } 52 | }() 53 | var b OrderBook 54 | err = restapi.GetJson(c, JsonDepth, &b) 55 | check(err) 56 | for _, ask := range b.Asks { 57 | var o xgen.Order 58 | o.Price, err = strconv.Atof64(ask[Price]) 59 | check(err) 60 | o.Amount, err = strconv.Atof64(ask[Amount]) 61 | check(err) 62 | x.SellTree = append(x.SellTree, o) 63 | } 64 | for _, bid := range b.Bids { 65 | var o xgen.Order 66 | o.Price, err = strconv.Atof64(bid[Price]) 67 | check(err) 68 | o.Amount, err = strconv.Atof64(bid[Amount]) 69 | check(err) 70 | x.BuyTree = append(x.BuyTree, o) 71 | } 72 | if !x.Validate() { 73 | panic("Invalid Depth") 74 | } 75 | sort.Sort(x.BuyTree) 76 | sort.Sort(x.SellTree) 77 | x.BuyTree.Reverse() 78 | return 79 | } 80 | 81 | // GetBalance retrieves the account balance. 82 | func GetBalance(c appengine.Context, login xgen.Credentials) (x xgen.Balance, err os.Error) { 83 | defer func() { 84 | if e, ok := recover().(os.Error); ok { 85 | err = e 86 | } 87 | }() 88 | var b Balance 89 | err = restapi.PostJson(c, JsonBalance, map[string][]string{"name": {login.Username}, "pass": {login.Password}}, &b) 90 | check(err) 91 | x[xgen.BTC], err = strconv.Atof64(b.BTC) 92 | check(err) 93 | x[xgen.USD], err = strconv.Atof64(b.USD) 94 | return 95 | } 96 | 97 | func (h OpenOrders) convert() (o xgen.OpenOrders) { // Convert tradehill.OpenOrders to xgen.OpenOrders 98 | var err os.Error 99 | o.Sell = make(map[string]xgen.OpenOrder) 100 | o.Buy = make(map[string]xgen.OpenOrder) 101 | for _, order := range h.Orders { 102 | var t xgen.OpenOrder 103 | t.Date = order.Date 104 | t.Price, err = strconv.Atof64(order.Price) 105 | check(err) 106 | t.Amount, err = strconv.Atof64(order.Amount) 107 | check(err) 108 | if order.OrderType == 1 { // Sell order 109 | o.Sell[strconv.Itoa64(order.Oid)] = t 110 | } else if order.OrderType == 2 { // Buy order 111 | o.Buy[strconv.Itoa64(order.Oid)] = t 112 | } else { 113 | panic("Invalid order type") 114 | } 115 | } 116 | return 117 | } 118 | 119 | // GetOpenOrders retrieves a list of all open orders. 120 | func GetOpenOrders(c appengine.Context, login xgen.Credentials) (x xgen.OpenOrders, err os.Error) { 121 | defer func() { 122 | if e, ok := recover().(os.Error); ok { 123 | err = e 124 | } 125 | }() 126 | var openOrders OpenOrders 127 | err = restapi.PostJson(c, JsonOrders, map[string][]string{"name": {login.Username}, "pass": {login.Password}}, &openOrders) 128 | check(err) 129 | x = openOrders.convert() 130 | return 131 | } 132 | 133 | // CancelOrder cancels an open order. 134 | func CancelOrder(c appengine.Context, login xgen.Credentials, oid string) (x xgen.OpenOrders, err os.Error) { 135 | defer func() { 136 | if e, ok := recover().(os.Error); ok { 137 | err = e 138 | } 139 | }() 140 | var openOrders OpenOrders 141 | err = restapi.PostJson(c, JsonCancel, map[string][]string{"name": {login.Username}, "pass": {login.Password}, "oid": {oid}}, &openOrders) 142 | check(err) 143 | x = openOrders.convert() // Note: Canceling an order may take up to 1 second. During that time the order is considered active and will be returned as active by GetOrders. 144 | return 145 | } 146 | 147 | // Buy opens a new order to buy BTC. 148 | func Buy(c appengine.Context, login xgen.Credentials, price float64, amount float64) (x xgen.OpenOrders, err os.Error) { 149 | defer func() { 150 | if e, ok := recover().(os.Error); ok { 151 | err = e 152 | } 153 | }() 154 | var openOrders OpenOrders 155 | err = restapi.PostJson(c, JsonBuy, map[string][]string{"name": {login.Username}, "pass": {login.Password}, 156 | "price": {strconv.Ftoa64(price, 'f', -1)}, "amount": {strconv.Ftoa64(amount, 'f', -1)}}, &openOrders) 157 | check(err) 158 | x = openOrders.convert() 159 | return 160 | } 161 | 162 | // Sell opens a new order to sell BTC. 163 | func Sell(c appengine.Context, login xgen.Credentials, price float64, amount float64) (x xgen.OpenOrders, err os.Error) { 164 | defer func() { 165 | if e, ok := recover().(os.Error); ok { 166 | err = e 167 | } 168 | }() 169 | var openOrders OpenOrders 170 | err = restapi.PostJson(c, JsonSell, map[string][]string{"name": {login.Username}, "pass": {login.Password}, 171 | "price": {strconv.Ftoa64(price, 'f', -1)}, "amount": {strconv.Ftoa64(amount, 'f', -1)}}, &openOrders) 172 | check(err) 173 | x = openOrders.convert() 174 | return 175 | } 176 | -------------------------------------------------------------------------------- /xgen/exchange.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | // Package xgen provides generic structures for storing data from various Bitcoin exchanges 5 | package xgen 6 | 7 | // TODO: Store monetary values as fixed points (instead of floating points), at least if native support gets added to Go 8 | 9 | import "appengine/datastore" 10 | 11 | // Quote is a struct representing the best available buy and sell prices at the time. 12 | type Quote struct { 13 | Date datastore.Time 14 | HighestBuy float64 15 | LowestSell float64 16 | Last float64 17 | } 18 | 19 | // Validate method checks that |Quote| values are valid (non-zero). 20 | func (t Quote) Validate() bool { 21 | if t.HighestBuy == 0 || t.LowestSell == 0 || t.Last == 0 { 22 | return false 23 | } 24 | return true 25 | } 26 | 27 | // Order is a struct representing a single limit order from the order book. 28 | type Order struct { 29 | Price float64 // Price per BTC 30 | Amount float64 // Number of BTC 31 | } 32 | type orders []Order 33 | 34 | // OrderBook is a struct representing a limit order book. 35 | type OrderBook struct { 36 | BuyTree orders // Bids 37 | SellTree orders // Asks 38 | } 39 | 40 | // Methods needed for sorting the orders in the order book (by price). 41 | func (m orders) Len() int { return len(m) } 42 | func (m orders) Less(i, j int) bool { return m[i].Price < m[j].Price } 43 | func (m orders) Swap(i, j int) { m[i], m[j] = m[j], m[i] } 44 | 45 | // Reverse will reverse the order of orders in the order book. 46 | func (m orders) Reverse() { 47 | for i, j := 0, len(m)-1; i < j; i, j = i+1, j-1 { 48 | m[i], m[j] = m[j], m[i] 49 | } 50 | } 51 | 52 | // Validate method checks that |OrderBook| is valid (not empty and non-zero values). 53 | func (m OrderBook) Validate() bool { 54 | if len(m.SellTree) == 0 || len(m.BuyTree) == 0 { 55 | return false 56 | } 57 | for _, ask := range m.SellTree { 58 | if ask.Price == 0 || ask.Amount == 0 { 59 | return false 60 | } 61 | } 62 | for _, bid := range m.BuyTree { 63 | if bid.Price == 0 || bid.Amount == 0 { 64 | return false 65 | } 66 | } 67 | return true 68 | } 69 | 70 | // Trade is a struct representing a historical trade. 71 | type Trade struct { 72 | Date int64 // Unix timestamp 73 | Tid int64 // Unique trade id 74 | Price float64 // Price in USD (or other currency) 75 | Amount float64 // Amount of BTC 76 | } 77 | 78 | // UniqueKey is a method identifying the trade id, to be used as a key by the datastore. 79 | func (t Trade) UniqueKey() (string, int64) { 80 | return "", t.Tid 81 | } 82 | 83 | // RecentTrades is a struct representing a slice of historical trades. 84 | type RecentTrades struct { 85 | Trades []Trade 86 | } 87 | 88 | // Validate method checks that |RecentTrades| is valid (not empty and non-zero values). 89 | func (t RecentTrades) Validate() bool { 90 | if len(t.Trades) == 0 { 91 | return false 92 | } 93 | for _, trade := range t.Trades { 94 | // In theory zero is a valid value for trade.Date, but in practice it means something went wrong (same for trade.Tid) 95 | if trade.Date == 0 || trade.Tid == 0 || trade.Price == 0 || trade.Amount == 0 { 96 | return false 97 | } 98 | } 99 | return true 100 | } 101 | -------------------------------------------------------------------------------- /xgen/tradeaccount.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Teppo Salonen. All rights reserved. 2 | // This file is part of ArBit and distributed under the terms of the MIT/X11 license. 3 | 4 | package xgen 5 | 6 | // TODO: Store monetary values as fixed points (instead of floating points), at least if native support gets added to Go 7 | 8 | // List of currencies. 9 | const ( 10 | BTC = iota 11 | USD 12 | 13 | NumCurrencies 14 | ) 15 | 16 | // Credentials stores the username and password for the account. 17 | type Credentials struct { 18 | Username string 19 | Password string 20 | } 21 | 22 | // Balance contains the amount of each currency in the account. 23 | type Balance [NumCurrencies]float64 24 | 25 | // OpenOrder contains basic information of an order. 26 | type OpenOrder struct { 27 | Date int64 // Timestamp for when the order was created 28 | Price float64 // Price per BTC (usually in USD) 29 | Amount float64 // Amount of BTC 30 | } 31 | 32 | // OpenOrders is a struct representing all our open buy and sell orders in the account. 33 | type OpenOrders struct { 34 | Buy map[string]OpenOrder // Each order has a unique ID, used as the map key 35 | Sell map[string]OpenOrder // Some exchanges don't use integers for the Order ID's, therefore using string instead 36 | } 37 | --------------------------------------------------------------------------------