Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
maksym committed Sep 19, 2017
0 parents commit ab82937
Show file tree
Hide file tree
Showing 7 changed files with 341 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/target
/classes
/checkouts
pom.xml
pom.xml.asc
*.jar
*.class
/.lein-*
/.nrepl-port
.hgignore
.hg/
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Change Log
All notable changes to this project will be documented in this file. This change log follows the conventions of [keepachangelog.com](http://keepachangelog.com/).

## [Unreleased]
### Added
### Changed
### Removed
### Fixed

## [0.1.0] - 2017-09-19
### Added
- Initial API implementation

[Unreleased]: https://github.com/keymone/krak/compare/0.1.0...HEAD
[0.1.0]: https://github.com/keymone/krak/compare/00000000...0.1.0
8 changes: 8 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Copyright 2017 Maksym Melnychok

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.

46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# krak

[Kraken API](https://www.kraken.com/help/api) in Clojure.

## Installation

Add the following to your project.clj's dependencies:

![](https://clojars.org/org.clojars.keymone/krak/latest-version.svg)

## Dependencies

- org.clojure/clojure
- org.clojure/data.codec
- org.clojure/data.json
- http-kit
- pandect

## Examples

```clojure
(require '[krak.client :as k])

(get-in (k/time) [:data "result" "unixtime"])
;; => 1505839538

(get-in (k/asset-pairs :pair ["BCHEUR"]) [:data "result" "BCHEUR" "fees_maker" 0])
;; => [0 0.16]

;; setup client context with API credentials and optional
;; nonce offset (nonce-offset named argument)
(def kctx (k/new-context api-key secret-key))

(get-in (k/balance kctx) [:data "result"])
;; => {"XXBT" "millions", "XETH" "billions"}
```

## License

Copyright 2017 Maksym Melnychok

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.
10 changes: 10 additions & 0 deletions project.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
(defproject krak "0.1.0"
:description "Kraken API"
:url "http://github.com/keymone/krak"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[http-kit "2.2.0"]
[pandect "0.6.1"]
[org.clojure/data.codec "0.1.0"]
[org.clojure/data.json "0.2.6"]])
185 changes: 185 additions & 0 deletions src/krak/client.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
(ns krak.client
(:require [krak.intern.client :refer :all]))


(defn new-context [api-key secret-key & {:keys [nonce-offset rate-counter]
:or {nonce-offset 0 rate-counter 0}}]
(atom {:api-key api-key
:secret-key secret-key
:rate-counter rate-counter
:nonce-offset (long nonce-offset)}))

(def endpoints
[
;; PUBLIC
{:fn-name 'time
:path "/0/public/Time"
:inputs {}}
{:fn-name 'assets
:path "/0/public/Assets"
:inputs {:info {:optional true}
:aclass {:optional true}
:asset {:optional true}}}
{:fn-name 'asset-pairs
:path "/0/public/AssetPairs"
:inputs {:info {:optional true
:vals ["info" "leverage" "fees" "margin"]}
:pair {:optional true
:prepare-fn cj}}}
{:fn-name 'ticker
:path "/0/public/Ticker"
:inputs {:pair {:optional true
:prepare-fn cj}}}
{:fn-name 'ohlc
:path "/0/public/OHLC"
:inputs {:pair {}
:interval {:optional true}
:since {:optional true}}}
{:fn-name 'depth
:path "/0/public/Depth"
:inputs {:pair {}
:count {:optional true}}}
{:fn-name 'trades
:path "/0/public/Trades"
:inputs {:pair {}
:since {:optional true}}}
{:fn-name 'spread
:path "/0/public/Spread"
:inputs {:pair {}
:since {:optional true}}}

;; PRIVATE
{:fn-name 'balance
:path "/0/private/Balance"
:signature true
:inputs {}}
{:fn-name 'trade-balance
:path "/0/private/TradeBalance"
:signature true
:inputs {:aclass {:optional true}
:asset {}}}
{:fn-name 'open-orders
:path "/0/private/OpenOrders"
:signature true
:inputs {:trades {:optional true}
:userref {:optional true}}}
{:fn-name 'closed-orders
:path "/0/private/ClosedOrders"
:signature true
:inputs {:trades {:optional true}
:userref {:optional true}
:start {:optional true}
:end {:optional true}
:ofs {}
:closetime {:optional true}}}
{:fn-name 'query-orders
:path "/0/private/QueryOrders"
:signature true
:inputs {:trades {:optional true}
:userref {:optional true}
:txid {:prepare-fn cj}}}
{:fn-name 'trades-history
:path "/0/private/TradesHistory"
:signature true
:inputs {:type {:optional true}
:trades {:optional true}
:start {:optional true}
:end {:optional true}
:ofs {}}}
{:fn-name 'query-trades
:path "/0/private/QueryTrades"
:signature true
:inputs {:trades {:optional true}
:txid {:prepare-fn cj}}}
{:fn-name 'open-positions
:path "/0/private/OpenPositions"
:signature true
:inputs {:txid {:prepare-fn cj}
:docalcs {:optional true}}}
{:fn-name 'ledgers
:path "/0/private/Ledgers"
:signature true
:inputs {:aclass {:optional true}
:asset {:optional true}
:type {:optional true}
:start {:optional true}
:end {:optional true}
:ofs {}}}
{:fn-name 'query-ledgers
:path "/0/private/QueryLedgers"
:signature true
:inputs {:id {:prepare-fn cj}}}
{:fn-name 'trade-volume
:path "/0/private/TradeVolume"
:signature true
:inputs {:pair {:optional true
:prepare-fn cj}
:fee-info {:optional true}}}
{:fn-name 'add-order
:path "/0/private/AddOrder"
:signature true
:inputs {:pair {}
:type {}
:ordertype {}
:price {:optional true}
:price2 {:optional true}
:volume {}
:leverage {:optional true}
:oflags {:optional true}
:starttm {:optional true}
:expiretm {:optional true}
:userref {:optional true}
:validate {:optional true}}}
{:fn-name 'cancel-order
:path "/0/private/CancelOrder"
:signature true
:inputs {:txid {}}}

;; FUNDING
{:fn-name 'deposit-methods
:path "/0/private/DepositMethods"
:signature true
:inputs {:aclass {:optional true}
:asset {}}}
{:fn-name 'deposit-addresses
:path "/0/private/DepositAdresses"
:signature true
:inputs {:aclass {:optional true}
:asset {}
:method {}
:new {:optional true}}}
{:fn-name 'deposit-status
:path "/0/private/DepositStatus"
:signature true
:inputs {:aclass {:optional true}
:asset {}
:method {}}}
{:fn-name 'withdraw-info
:path "/0/private/WithdrawInfo"
:signature true
:inputs {:aclass {:optional true}
:asset {}
:key {}
:amount {}}}
{:fn-name 'withdraw
:path "/0/private/Withdraw"
:signature true
:inputs {:aclass {:optional true}
:asset {}
:key {}
:amount {}}}
{:fn-name 'withdraw-status
:path "/0/private/WithdrawStatus"
:signature true
:inputs {:aclass {:optional true}
:asset {}
:method {:optional true}}}
{:fn-name 'withdraw-cancel
:path "/0/private/WithdrawCancel"
:signature true
:inputs {:aclass {:optional true}
:asset {}
:refid {}}}
])

(dorun (map register-endpoint endpoints))
66 changes: 66 additions & 0 deletions src/krak/intern/client.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
(ns krak.intern.client
(:require [org.httpkit.client :as http]
[pandect.algo.sha512 :refer [sha512-hmac-bytes]]
[pandect.algo.sha256 :refer [sha256-bytes]]
[clojure.data.codec.base64 :as b64]
[clojure.data.json :as json]
[clojure.set :as set]))

(def KRAKEN-API "https://api.kraken.com")

;; API-Key = API key
;; API-Sign = Message signature using HMAC-SHA512 of
;; (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
(defn- sign-request [api-key secret-key path data nonce]
(let [secret-bytes (b64/decode (.getBytes secret-key))
nd-digest (sha256-bytes (str nonce data))
path-digest (byte-array (concat (.getBytes path) nd-digest))
hmac-bytes (sha512-hmac-bytes path-digest secret-bytes)
signature (String. (b64/encode hmac-bytes))]
{"API-KEY" api-key
"API-Sign" signature}))

(defn cj [coll]
(if (empty? coll) nil
(clojure.string/join "," coll)))

(defn- prepare-opt [[key {:keys [optional prepare-fn]}] data]
(if (and (not optional) (nil? data))
(throw (Exception. (str "must provide " key)))
[key
(if-not prepare-fn data
(try (prepare-fn data)
(catch Exception e
(throw (Exception.
(str "failed prepare-fn " key " " (ex-data e)))))))]))

(defn- prepare-opts [inputs opts]
(let [ok (set (keys opts))
ik (set (keys inputs))]
(if-not (set/subset? ok ik)
(throw (Exception. (str "unknown arguments: " (set/difference ok ik))))))
(let [pairs (remove (comp nil? second)
(map #(prepare-opt %
((first %) opts))
inputs))]
(into {} pairs)))

(defn- endpoint-fn [path inputs signature]
(if signature
(fn [ctx & {:as opts}]
(let [{:keys [api-key secret-key nonce-offset]} @ctx
nonce (+ nonce-offset (System/currentTimeMillis))
data (#'http/query-string
(assoc (prepare-opts inputs opts) :nonce nonce))
headers (sign-request api-key secret-key path data nonce)]
(swap! ctx update :rate-counter + 2)
(let [response @(http/post (str KRAKEN-API path)
{:body data :headers headers})]
(assoc response :data (json/read-str (:body response))))))
(fn [& {:as opts}]
(let [data (#'http/query-string (prepare-opts inputs opts))
response @(http/post (str KRAKEN-API path) {:body data})]
(assoc response :data (json/read-str (:body response)))))))

(defn register-endpoint [{:keys [fn-name path inputs signature]}]
(intern *ns* fn-name (endpoint-fn path inputs signature)))

0 comments on commit ab82937

Please sign in to comment.