AverageTrueRangeIndicator::__invoke()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 0
cts 21
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 21
nc 6
nop 2
crap 20
1
<?php
2
3
namespace Laratrade\Indicators;
4
5
use Illuminate\Support\Collection;
6
use Laratrade\Indicators\Contracts\Indicator;
7
use Laratrade\Indicators\Exceptions\NotEnoughDataException;
8
use Throwable;
9
10
class AverageTrueRangeIndicator implements Indicator
11
{
12
    /**
13
     * Invoke the indicator.
14
     *
15
     * @param Collection $ohlcv
16
     * @param int        $timePeriod
17
     *
18
     * @return int
19
     *
20
     * @throws Throwable
21
     */
22
    public function __invoke(Collection $ohlcv, int $timePeriod = 14): int
23
    {
24
        $close      = $ohlcv->get('close');
25
        $closeCount = count($close);
26
27
        if ($timePeriod > $closeCount) {
28
            $timePeriod = round($closeCount / 2);
29
        }
30
31
        $atr = trader_atr(
32
            $ohlcv->get('high'),
33
            $ohlcv->get('low'),
34
            $ohlcv->get('close'),
35
            $timePeriod
36
        );
37
38
        throw_unless($atr, NotEnoughDataException::class);
39
40
        $currentValue  = array_pop($close);
41
        $previousValue = array_pop($close);
42
        $atrValue      = array_pop($atr);
43
44
        $upside   = ($currentValue - ($previousValue + $atrValue));
45
        $downside = ($previousValue - ($currentValue + $atrValue));
46
47
        if ($upside > 0) {
48
            return static::BUY;
49
        } elseif ($downside > 0) {
50
            return static::SELL;
51
        }
52
53
        return static::HOLD;
54
    }
55
}
56