File tree Expand file tree Collapse file tree 1 file changed +57
-12
lines changed
pub/bfx/src/Bfx/Indicator Expand file tree Collapse file tree 1 file changed +57
-12
lines changed Original file line number Diff line number Diff line change 3
3
module Bfx.Indicator.Ma
4
4
( Ma (.. ),
5
5
MaPeriod (.. ),
6
- ma ,
6
+ defMaPeriod ,
7
+ mkMaConduit ,
8
+ mkMa ,
7
9
)
8
10
where
9
11
10
12
import Bfx.Data.Type
13
+ import Conduit ((.|) )
14
+ import qualified Conduit as C
11
15
import qualified Data.Map as Map
12
16
import qualified Data.Vector as V
13
17
import Functora.Money
@@ -20,29 +24,70 @@ newtype Ma = Ma
20
24
deriving stock
21
25
( Eq ,
22
26
Ord ,
27
+ Show ,
28
+ Read ,
23
29
Data ,
24
30
Generic
25
31
)
26
32
27
33
newtype MaPeriod = MaPeriod
28
34
{ unMaPeriod :: Natural
29
35
}
30
- deriving newtype
36
+ deriving stock
31
37
( Eq ,
32
38
Ord ,
33
39
Show ,
34
- Num ,
35
- Real ,
36
- Enum ,
37
- Integral
38
- )
39
- deriving stock
40
- ( Data ,
40
+ Read ,
41
+ Data ,
41
42
Generic
42
43
)
43
44
44
- ma :: MaPeriod -> NonEmpty Candle -> Map UTCTime Ma
45
- ma period candles =
45
+ defMaPeriod :: MaPeriod
46
+ defMaPeriod = MaPeriod 14
47
+
48
+ mkMaConduit ::
49
+ ( Monad m
50
+ ) =>
51
+ (a -> Candle ) ->
52
+ MaPeriod ->
53
+ C. ConduitT a (a , Ma ) m ()
54
+ mkMaConduit mkCandle per =
55
+ C. slidingWindowC period
56
+ .| ( whileM $ do
57
+ mcandles <- fmap (>>= nonEmpty) C. await
58
+ case mcandles of
59
+ Just candles | length candles == period -> do
60
+ C. yield
61
+ ( last candles,
62
+ Ma
63
+ . QuotePerBase
64
+ $ ( sum
65
+ $ fmap
66
+ ( unQuotePerBase
67
+ . candleClose
68
+ . mkCandle
69
+ )
70
+ candles
71
+ )
72
+ / from @ Natural @ (Ratio Natural )
73
+ ( unsafeFrom
74
+ @ Int
75
+ @ Natural
76
+ period
77
+ )
78
+ )
79
+ pure True
80
+ _ ->
81
+ pure False
82
+ )
83
+ where
84
+ period =
85
+ case unsafeFrom @ Natural @ Int $ unMaPeriod per of
86
+ x | x < 1 -> error $ " Bad MA period " <> inspect period
87
+ x -> x
88
+
89
+ mkMa :: MaPeriod -> NonEmpty Candle -> Map UTCTime Ma
90
+ mkMa period candles =
46
91
if stopAtIdx < 0 || maPeriod < 1
47
92
then mempty
48
93
else
@@ -53,7 +98,7 @@ ma period candles =
53
98
0
54
99
mempty
55
100
where
56
- maPeriod = Prelude. fromIntegral period
101
+ maPeriod = unsafeFrom @ Natural @ Int $ unMaPeriod period
57
102
stopAtIdx = length candles - maPeriod
58
103
59
104
unsafeMa ::
You can’t perform that action at this time.
0 commit comments