1 {-# LANGUAGE FlexibleContexts, ViewPatterns, UndecidableInstances #-}
2 module Cryptsy
.API
.Public
.OrderBook
3 ( module Cryptsy
.API
.Public
.OrderBook
4 , module Cryptsy
.API
.Public
.Types
.Monad
5 , module Cryptsy
.API
.Public
.Types
.Num
6 , module Cryptsy
.API
.Public
.Types
.Order
11 import Data
.Aeson
(FromJSON
(..), Value
, withObject
, (.:))
12 import Data
.Aeson
.Types
(Parser
)
15 import Control
.Applicative
((<*>))
16 import Control
.Monad
(fail, (>>=))
17 import Data
.Function
(($))
18 import Data
.Functor
((<$>))
19 import Data
.List
((++))
20 import Data
.Traversable
(mapM)
22 import Text
.Show (Show)
25 import Data
.Text
(Text
, pack
, unpack
)
27 -- unordered-containers
28 import Data
.HashMap
.Strict
(toList
)
31 import Data
.Vector
(Vector
)
34 import Cryptsy
.API
.Public
.Internal
35 import Cryptsy
.API
.Public
.Types
.Monad
36 import Cryptsy
.API
.Public
.Types
.Num
37 import Cryptsy
.API
.Public
.Types
.Order
39 -- |general order book
40 data GOrderBook p q t
= OrderBook
43 , obPrimaryName
:: Text
44 , obPrimaryCode
:: Text
45 , obSecondaryName
:: Text
46 , obSecondaryCode
:: Text
47 , obSellOrders
:: Vector
(GOrder p q t
)
48 , obBuyOrders
:: Vector
(GOrder p q t
)
51 -- |default order book
52 type OrderBook
= GOrderBook CryptsyNum CryptsyNum CryptsyNum
54 instance FromJSON
(GOrder p q t
) => FromJSON
(GOrderBook p q t
) where
55 parseJSON
= parseOrderBook parseJSON
57 -- |Build parser for orderbook from parser for a single order.
58 parseOrderBook
:: (Value
-> Parser
(GOrder p q t
)) -- ^ order parser
59 -> Value
-> Parser
(GOrderBook p q t
)
60 parseOrderBook parser
=
61 withObject
"OrderBook" $ \o
-> OrderBook
<$>
62 o
.: pack
"marketid" <*>
64 o
.: pack
"primaryname" <*>
65 o
.: pack
"primarycode" <*>
66 o
.: pack
"secondaryname" <*>
67 o
.: pack
"secondarycode" <*>
68 (o
.: pack
"sellorders" >>= parseSellOrders
) <*>
69 (o
.: pack
"buyorders" >>= parseBuyOrders
)
71 parseOrders
= mapM parser
72 parseSellOrders
= withNullableArray
"sellorders" $ parseOrders
73 parseBuyOrders
= withNullableArray
"buyorders" $ parseOrders
75 -- |single orderbook API request
76 singleOrderBook
:: FromJSON
(GOrderBook p q t
)
78 -> PubCryptsy
(GOrderBook p q t
)
79 singleOrderBook
(unpack
-> reqMarket
) =
80 pubCryptsy orderBookURL parseSingleOrderBook
82 orderBookURL
= pubURL
$ "singleorderdata&marketid=" ++ reqMarket
83 parseSingleOrderBook
= withObject dataStr
$ \o
->
85 [] -> fail "No order book returned."
86 [(_
, v
)] -> parseJSON v
87 _
-> fail "Multiple order books returned."