Bring parse call into common logic.
[haskell-cryptsy-api.git] / Cryptsy / API / Public / OrderBook.hs
blobffba3e7dac1a2c7d11899883c2290bfbdb2a887f
1 module Cryptsy.API.Public.OrderBook
2 ( GOrderBook(..), OrderBook
3 , withComponents, withOrder
4 , module Cryptsy.API.Public.Order
5 -- |Re-export from Cyptsy.API.Public
6 , CryptsyNum(..)
7 -- |Re-exported from Data.Aeson
8 , FromJSON(..), Value, Object
9 -- |Re-export from Data.Text
10 , Text
11 -- |Re-export from Data.Vector
12 , Vector
14 where
16 -- aeson
17 import Data.Aeson (FromJSON(..), Value, Object, withObject, (.:))
18 import Data.Aeson.Types (Parser)
20 -- base
21 import Control.Applicative ((<*>))
22 import Control.Monad ((>>=))
23 import Data.Function (($))
24 import Data.Functor ((<$>))
25 import Data.Traversable (mapM)
26 import Prelude ()
27 import Text.Show (Show)
29 -- text
30 import Data.Text (Text, pack)
32 -- vector
33 import Data.Vector (Vector)
35 -- this package
36 import Cryptsy.API.Public (CryptsyNum(..), withNullableArray)
37 import Cryptsy.API.Public.Order (GOrder(Order), Order)
39 -- |general order book
40 data GOrderBook p q t = OrderBook
41 { marketid :: Text
42 , label :: Text
43 , primaryname :: Text
44 , primarycode :: Text
45 , secondaryname :: Text
46 , secondarycode :: Text
47 , sellorders :: Vector (GOrder p q t)
48 , buyorders :: Vector (GOrder p q t)
49 } deriving Show
51 -- |default order book
52 type OrderBook = GOrderBook CryptsyNum CryptsyNum CryptsyNum
54 instance (FromJSON p, FromJSON q, FromJSON t) =>
55 FromJSON (GOrderBook p q t)
56 where
57 parseJSON = withObject "OrderBook" $ withComponents parseJSON
59 -- |Build parser for orderbook from parser for a single order.
60 withComponents :: (Value -> Parser (GOrder p q t)) -- ^ order parser
61 -> Object -> Parser (GOrderBook p q t)
62 withComponents parseOrder o =
63 OrderBook <$>
64 o .: pack "marketid" <*>
65 o .: pack "label" <*>
66 o .: pack "primaryname" <*>
67 o .: pack "primarycode" <*>
68 o .: pack "secondaryname" <*>
69 o .: pack "secondarycode" <*>
70 (o .: pack "sellorders" >>= parseSellOrders) <*>
71 (o .: pack "buyorders" >>= parseBuyOrders)
72 where
73 parseOrders = mapM parseOrder
74 parseSellOrders = withNullableArray "sellorders" $ parseOrders
75 parseBuyOrders = withNullableArray "buyorders" $ parseOrders
77 -- |Build parser for orderbook from parser for a single order object.
78 withOrder :: (Object -> Parser (GOrder p q t)) -- ^ order parser
79 -> Object -> Parser (GOrderBook p q t)
80 withOrder parseOrder = withComponents (withObject "Order" parseOrder)