First commit

This commit is contained in:
didier amyot committed 2018-05-21 16:42:51 -04:00
commit 8fb9335411
10 files changed
+468

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
(ns book.core
(:require [book.order]
[clojure.spec.alpha :as s]
[clojure.edn :as edn])
(:gen-class))
;; Let say a book is two collections. The first called
;; sell-book contains all the sell orders. The second
;; called buy-book contains all the buy orders.
(defn create-book [& args]
(let [cmp #(< (:price %1) (:price %2))]
(apply sorted-set-by cmp args)))
(def book {:sell (create-book) :buy (create-book)})
(defn buy? [order]
(= :buy (:type order)))
(defn create-trade [order-to-fulfill book-order]
#:book.order{:type (:type book-order)
:quantity (:quantity order-to-fulfill)
:price (min (:price order-to-fulfill) (:price book-order))
:order-id (:book.order/id order-to-fulfill)
:book-id (:book.order/id book-order)})
(defn create-sell-trade-factory [order-to-fulfill]
(fn [trade book-order]
(let [qtn-to-fulfill (min (:quantity book-order) (- (:quantity order-to-fulfill) (:already-fulfilled trade 0)))
can-fulfill? (< (:price book-order) (:price order-to-fulfill))]
(when (and can-fulfill? (< qtn-to-fulfill 0))
#:book.order{:type :sell
:quantity qtn-to-fulfill
:price (min (:price book-order) (:price order-to-fulfill))
:order-id (:book.order/id order-to-fulfill)
:book-id (:book.order/id book-order)}))))
(defn create-sell-trades [order-to-fulfill sell-book]
(take-while nil?
(reductions (create-sell-trade-factory order-to-fulfill) sell-book)))
(defn partial-trade? [trade order]
(not= (:quantity order) (:book.order/quantity trade)))
(defn compute-partial-order [order trade]
(assoc order :quantity (- (:quantity order) (:book.order/quantity trade 0))))
(defn compute-new-sell-book-after-trades [sell-book trades]
(let [new-book (drop (-> trades count dec) sell-book)
possible-partial-trade (last trades)]
(if (partial-trade? possible-partial-trade (first new-book))
(conj (rest new-book) (compute-partial-order (first new-book) possible-partial-trade))
(rest new-book))))
(defn match-buy-order-in-sell-book [sell-book order]
(let [trades (create-trade order (first sell-book))
trades (create-sell-trades order sell-book)
new-book (compute-new-sell-book-after-trades sell-book trades)]
[trades new-book]))
(defn place-buy-order [book order]
(match-buy-order-in-sell-book (:sell book) order)
(println :bingo)) ;; should return multiple "trade" and a new book
(defn place-order [book order]
(if (buy? order)
(place-buy-order book order)))
(defn -main
[& args]
(let [order (-> args first edn/read-string)]
(if (not (s/valid? :book.order/order order))
(println "invalid order :( ")
(println (place-order book order)))))