Simplify main to just active tests.
[haskell-cryptsy-api.git] / Cryptsy / API / Public / OrderBook.hs
blob9e5f048026e0d56940f9f36a581e3e154d0392ed
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
8 where
10 -- aeson
11 import Data.Aeson (FromJSON(..), Value, withObject, (.:))
12 import Data.Aeson.Types (Parser)
14 -- base
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)
21 import Prelude ()
22 import Text.Show (Show)
24 -- text
25 import Data.Text (Text, pack, unpack)
27 -- unordered-containers
28 import Data.HashMap.Strict (toList)
30 -- vector
31 import Data.Vector (Vector)
33 -- this package
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
41 { obMarketId :: Text
42 , obLabel :: Text
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)
49 } deriving Show
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" <*>
63 o .: pack "label" <*>
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 )
70 where
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)
77 => Text -- ^ marketid
78 -> PubCryptsy (GOrderBook p q t)
79 singleOrderBook (unpack -> reqMarket) =
80 pubCryptsy orderBookURL parseSingleOrderBook
81 where
82 orderBookURL = pubURL $ "singleorderdata&marketid=" ++ reqMarket
83 parseSingleOrderBook = withObject dataStr $ \o ->
84 case toList o of
85 [] -> fail "No order book returned."
86 [(_, v)] -> parseJSON v
87 _ -> fail "Multiple order books returned."