Finance-Alpaca

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN


    **Note**: This is a false value by default.

## `account( )`

    my $acct = $camelid->account( );
    CORE::say sprintf 'I can%s short!', $acct->shorting_enabled ? '' : 'not';

Returns a [Finance::Alpaca::Struct::Account](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3AAccount) object.

The account endpoint serves important information related to an account,
including account status, funds available for trade, funds available for
withdrawal, and various flags relevant to an account’s ability to trade.

## `clock( )`

    my $clock = $camelid->clock();
    say sprintf
        $clock->timestamp->strftime('It is %l:%M:%S %p on a %A and the market is %%sopen!'),
        $clock->is_open ? '' : 'not ';

Returns a [Finance::Alpaca::Struct::Clock](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3AClock) object.

The clock endpoint serves the current market timestamp, whether or not the
market is currently open, as well as the times of the next market open and
close.

## `calendar( [...] )`

        my @days = $camelid->calendar(
            start => Time::Moment->now,
            end   => Time::Moment->now->plus_days(14)
        );
        for my $day (@days) {
            say sprintf '%s the market opens at %s Eastern',
                $day->date, $day->open;
        }

Returns a list of [Finance::Alpaca::Struct::Calendar](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3ACalendar) objects.

The calendar endpoint serves the full list of market days from 1970 to 2029.

The following parameters are accepted:

- `start` - The first date to retrieve data for (inclusive); Time::Moment object or RFC3339 string
- `end` - The last date to retrieve data for (inclusive); Time::Moment object or RFC3339 string

Both listed parameters are optional. If neither is provided, the calendar will
begin on January 1st, 1970.

## `assets( [...] )`

    say $_->symbol
        for sort { $a->symbol cmp $b->symbol } @{ $camelid->assets( status => 'active' ) };

Returns a list of [Finance::Alpaca::Struct::Asset](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3AAsset) objects.

The assets endpoint serves as the master list of assets available for trade and
data consumption from Alpaca.

The following parameters are accepted:

- `status` - e.g. `active` or `inactive`. By default, all statuses are included
- `asset_class` - Defaults to `us_equity`

## `asset( ... )`

    my $msft = $camelid->asset('MSFT');

README.md  view on Meta::CPAN

    my %bars = $camelid->bars(
          symbol    => 'MSFT',
          timeframe => '1Min',
          start     => Time::Moment->now->with_hour(10),
          end       => Time::Moment->now->minus_minutes(20)
      );

Returns a list of [Finance::Alpaca::Struct::Bar](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3ABar) objects along with other
data.

The bar endpoint serves aggregate historical data for the requested securities.

The following parameters are accepted:

- `symbol` - The symbol to query for; this is required
- `start` - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required
- `end` - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required
- `limit` - Number of data points to return. Must be in range `1-10000`, defaults to `1000`
- `page_token` - Pagination token to continue from
- `timeframe` - Timeframe for the aggregation. Available values are: `1Min`, `1Hour`, and `1Day`; this is required

README.md  view on Meta::CPAN


    my %quotes = $camelid->quotes(
        symbol => 'MSFT',
        start  => Time::Moment->now->with_hour(10),
        end    => Time::Moment->now->minus_minutes(20)
    );

Returns a list of [Finance::Alpaca::Struct::Quote](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3AQuote) objects along with other
data.

The bar endpoint serves quote (NBBO) historical data for the requested
security.

The following parameters are accepted:

- `symbol` - The symbol to query for; this is required
- `start` - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required
- `end` - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required
- `limit` - Number of data points to return. Must be in range `1-10000`, defaults to `1000`
- `page_token` - Pagination token to continue from

README.md  view on Meta::CPAN


    my %trades = $camelid->trades(
        symbol => 'MSFT',
        start  => Time::Moment->now->with_hour(10),
        end    => Time::Moment->now->minus_minutes(20)
    );

Returns a list of [Finance::Alpaca::Struct::Trade](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3ATrade) objects along with other
data.

The bar endpoint serves historical trade data for a given ticker symbol on a
specified date.

The following parameters are accepted:

- `symbol` - The symbol to query for; this is required
- `start` - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required
- `end` - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required
- `limit` - Number of data points to return. Must be in range `1-10000`, defaults to `1000`
- `page_token` - Pagination token to continue from

README.md  view on Meta::CPAN


This method expects a code reference. This callback will receive all incoming
data.

## `orders( [...] )`

    my @orders = $camelid->orders( status => 'open' );

Returns a list of [Finance::Alpaca::Struct::Order](https://metacpan.org/pod/Finance%3A%3AAlpaca%3A%3AStruct%3A%3AOrder) objects.

The orders endpoint returns a list of orders for the account, filtered by the
supplied parameters.

The following parameters are accepted:

- `status` - Order status to be queried. `open`, `closed`, or `all`. Defaults to `open`.
- `limit` - The maximum number of orders in response. Defaults to `50` and max is `500`.
- `after` - The response will include only ones submitted after this timestamp (exclusive.)
- `until` - The response will include only ones submitted until this timestamp (exclusive.)
- `direction` - The chronological order of response based on the submission time. `asc` or `desc`. Defaults to `desc`.
- `nested` - Boolean value indicating whether the result will roll up multi-leg orders under the `legs( )` field of the primary order.

lib/Finance/Alpaca.pm  view on Meta::CPAN

            start => sub ( $ua, $tx ) {
                $tx->req->headers->header( 'APCA-API-KEY-ID'     => $s->keys->[0] ) if $s->has_keys;
                $tx->req->headers->header( 'APCA-API-SECRET-KEY' => $s->keys->[1] ) if $s->has_keys;
            }
        );
        return $ua;
    }
    has api_version => ( is => 'ro', isa => Enum [ 1, 2 ], required => 1, default => 2 );
    has paper => ( is => 'rw', isa => Bool, required => 1, default => 0, coerce => 1 );

    sub endpoint ($s) {
        $s->paper ? 'https://paper-api.alpaca.markets' : '';
    }
    has keys => ( is => 'rwp', isa => ArrayRef [ Str, 2 ], predicate => 1 );
    #
    sub account ($s) {
        my $tx = $s->ua->build_tx( GET => $s->endpoint . '/v2/account' );
        $tx = $s->ua->start($tx);
        return to_Account( $tx->result->json );
    }

    sub clock ($s) {
        my $tx = $s->ua->build_tx( GET => $s->endpoint . '/v2/clock' );
        $tx = $s->ua->start($tx);
        return to_Clock( $tx->result->json );
    }

    sub calendar ( $s, %params ) {
        my $params = '';
        $params .= '?' . join '&', map {
            $_ . '='
                . ( ref $params{$_} eq 'Time::Moment' ? $params{$_}->to_string() : $params{$_} )
        } keys %params if keys %params;
        my $tx = $s->ua->build_tx( GET => $s->endpoint . '/v2/calendar' . $params );
        $tx = $s->ua->start($tx);
        return @{ ( ArrayRef [Calendar] )->assert_coerce( $tx->result->json ) };
    }

    sub assets ( $s, %params ) {
        my $params = '';
        $params .= '?' . join '&', map {
            $_ . '='
                . ( ref $params{$_} eq 'Time::Moment' ? $params{$_}->to_string() : $params{$_} )
        } keys %params if keys %params;
        return @{
            ( ArrayRef [Asset] )->assert_coerce(
                $s->ua->get( $s->endpoint . '/v2/assets' . $params )->result->json
            )
        };

    }

    sub asset ( $s, $symbol_or_asset_id ) {
        my $res = $s->ua->get( $s->endpoint . '/v2/assets/' . $symbol_or_asset_id )->result;
        return $res->is_error ? () : to_Asset( $res->json );
    }

    sub bars ( $s, %params ) {
        my $symbol = delete $params{symbol};
        my $params = '';
        $params .= '?' . join '&', map {
            $_ . '='
                . (
                ref $params{$_} eq 'Time::Moment'

lib/Finance/Alpaca.pm  view on Meta::CPAN

        )->wait;
        $stream;
    }

    sub orders ( $s, %params ) {
        for ( keys %params ) {
            $params{$_} = $params{$_}->to_string() if ref $params{$_} eq 'Time::Moment';
        }
        return @{
            ( ArrayRef [Order] )->assert_coerce(
                $s->ua->get( $s->endpoint . '/v2/orders' => form => {%params} )->result->json
            )
        };
    }

    sub order_by_id ( $s, $order_id, $nested = 0 ) {
        my $res
            = $s->ua->get(
            $s->endpoint . '/v2/orders/' . $order_id => form => ( $nested ? { nested => 1 } : () ) )
            ->result;
        return $res->is_error ? () : to_Order( $res->json );
    }

    sub order_by_client_id ( $s, $order_id ) {
        my $res
            = $s->ua->get( $s->endpoint
                . '/v2/orders:by_client_order_id' => form => { client_order_id => $order_id } )
            ->result;
        return $res->is_error ? () : to_Order( $res->json );
    }

    sub create_order ( $s, %params ) {
        $params{extended_hours} = ( !!$params{extended_hours} ) ? 'true' : 'false'
            if defined $params{extended_hours};
        my $res = $s->ua->post( $s->endpoint . '/v2/orders' => json => \%params )->result;
        return $res->is_error ? $res->json : to_Order( $res->json );
    }

    sub replace_order ( $s, $order_id, %params ) {
        $params{extended_hours} = ( !!$params{extended_hours} ) ? 'true' : 'false'
            if defined $params{extended_hours};
        my $res
            = $s->ua->patch( $s->endpoint . '/v2/orders/' . $order_id => json => \%params )->result;
        return $res->is_error ? $res->json : to_Order( $res->json );
    }

    sub cancel_orders ($s) {
        my $res = $s->ua->delete( $s->endpoint . '/v2/orders' )->result;
        return $res->is_error
            ? $res->json
            : ( ArrayRef [ Dict [ body => Order, id => Uuid, status => Int ] ] )
            ->assert_coerce( $res->json );
    }

    sub cancel_order ( $s, $order_id ) {
        my $res = $s->ua->delete( $s->endpoint . '/v2/orders/' . $order_id )->result;
        return !$res->is_error;
    }

    sub positions ($s) {
        return
            @{ ( ArrayRef [Position] )
                ->assert_coerce( $s->ua->get( $s->endpoint . '/v2/positions' )->result->json ) };
    }

    sub position ( $s, $symbol_or_asset_id ) {
        my $res = $s->ua->get( $s->endpoint . '/v2/positions/' . $symbol_or_asset_id )->result;
        return $res->is_error ? () : to_Position( $res->json );
    }

    sub close_all_positions ( $s, $cancel_orders = !1 ) {
        my $res
            = $s->ua->delete(
            $s->endpoint . '/v2/positions' . ( $cancel_orders ? '?cancel_orders=true' : '' ) )
            ->result;
        return $res->is_error
            ? $res->json
            : ( ArrayRef [ Dict [ body => Order, id => Uuid, status => Int ] ] )
            ->assert_coerce( $res->json );
    }

    sub close_position ( $s, $symbol_or_asset_id, $qty = () ) {
        my $res
            = $s->ua->get(
            $s->endpoint . '/v2/positions/' . $symbol_or_asset_id . ( $qty ? '?qty=' . $qty : '' ) )
            ->result;
        return $res->is_error ? () : to_Order( $res->json );
    }

    sub portfolio_history ( $s, %params ) {
        $params{extended_hours} = ( !!$params{extended_hours} ) ? 'true' : 'false'
            if defined $params{extended_hours};
        $params{date_end}
            = ref $params{date_end} eq 'Time::Moment'
            ? $params{date_end}->strftime('%F')
            : $params{date_end}
            if defined $params{date_end};
        my $res = $s->ua->get( $s->endpoint . '/v2/account/portfolio/history' => json => \%params )
            ->result;
        return $res->is_error ? $res->json : (
            Dict [
                base_value      => Num,
                equity          => ArrayRef [Num],
                profit_loss     => ArrayRef [Num],
                profit_loss_pct => ArrayRef [Num],
                timeframe       => Str,
                timestamp       => ArrayRef [Timestamp]
            ]
        )->assert_coerce( $res->json );
    }

    sub watchlists ($s) {
        return
            @{ ( ArrayRef [Watchlist] )
                ->assert_coerce( $s->ua->get( $s->endpoint . '/v2/watchlists' )->result->json ) };
    }

    sub create_watchlist ( $s, $name, @symbols ) {
        my $res
            = $s->ua->post( $s->endpoint
                . '/v2/watchlists' => json =>
                { name => $name, ( @symbols ? ( symbols => \@symbols ) : () ) } )->result;
        return $res->is_error ? ( $res->json ) : to_Watchlist( $res->json );
    }

    sub delete_watchlist ( $s, $watchlist_id ) {
        my $res = $s->ua->delete( $s->endpoint . '/v2/watchlists/' . $watchlist_id )->result;
        return $res->is_error ? $res->json : 1;
    }

    sub watchlist ( $s, $watchlist_id ) {
        my $res = $s->ua->get( $s->endpoint . '/v2/watchlists/' . $watchlist_id )->result;
        return $res->is_error ? ( $res->json ) : to_Watchlist( $res->json );
    }

    sub update_watchlist ( $s, $watchlist_id, %params ) {
        my $res
            = $s->ua->put( $s->endpoint . '/v2/watchlists/' . $watchlist_id => json => {%params} )
            ->result;
        return $res->is_error ? ( $res->json ) : to_Watchlist( $res->json );
    }

    sub add_to_watchlist ( $s, $watchlist_id, $symbol ) {
        my $res
            = $s->ua->post(
            $s->endpoint . '/v2/watchlists/' . $watchlist_id => json => { symbol => $symbol } )
            ->result;
        return $res->is_error ? ( $res->json ) : to_Watchlist( $res->json );
    }

    sub remove_from_watchlist ( $s, $watchlist_id, $symbol ) {
        my $res = $s->ua->delete( $s->endpoint . '/v2/watchlists/' . $watchlist_id . '/' . $symbol )
            ->result;
        return $res->is_error ? ( $res->json ) : to_Watchlist( $res->json );
    }

    sub configuration ($s) {
        my $res = $s->ua->get( $s->endpoint . '/v2/account/configurations' )->result;
        return $res->is_error ? ( $res->json ) : to_Configuration( $res->json );
    }

    sub modify_configuration ( $s, %params ) {
        my $res = $s->ua->patch( $s->endpoint . '/v2/account/configurations' => json => {%params} )
            ->result;
        return $res->is_error ? ( $res->json ) : to_Configuration( $res->json );
    }

    sub activities ( $s, %params ) {
        $params{activity_types} = join ',', @{ $params{activity_types} } if $params{activity_types};
        my $params = '';
        $params .= '?' . join '&', map {
            $_ . '='
                . (
                  ref $params{$_} eq 'Time::Moment' ? $params{$_}->to_string()
                : ref $params{$_} eq 'ARRAY'        ? @{ $params{$_} }
                :                                     $params{$_}
                )
        } keys %params if keys %params;
        my $res = $s->ua->get(
            sprintf $s->endpoint . '/v2/account/activities%s',
            $params ? $params : ''
        )->result;
        return $res->is_error
            ? $res->json
            : map { $_->{activity_type} eq 'FILL' ? to_TradeActivity($_) : to_Activity($_) }
            @{ $res->json };
    }
}
1;
__END__

lib/Finance/Alpaca.pm  view on Meta::CPAN


=back

=head2 C<account( )>

    my $acct = $camelid->account( );
    CORE::say sprintf 'I can%s short!', $acct->shorting_enabled ? '' : 'not';

Returns a L<Finance::Alpaca::Struct::Account> object.

The account endpoint serves important information related to an account,
including account status, funds available for trade, funds available for
withdrawal, and various flags relevant to an account’s ability to trade.

=head2 C<clock( )>

    my $clock = $camelid->clock();
    say sprintf
        $clock->timestamp->strftime('It is %l:%M:%S %p on a %A and the market is %%sopen!'),
        $clock->is_open ? '' : 'not ';

Returns a L<Finance::Alpaca::Struct::Clock> object.

The clock endpoint serves the current market timestamp, whether or not the
market is currently open, as well as the times of the next market open and
close.

=head2 C<calendar( [...] )>

        my @days = $camelid->calendar(
            start => Time::Moment->now,
            end   => Time::Moment->now->plus_days(14)
        );
        for my $day (@days) {
            say sprintf '%s the market opens at %s Eastern',
                $day->date, $day->open;
        }

Returns a list of L<Finance::Alpaca::Struct::Calendar> objects.

The calendar endpoint serves the full list of market days from 1970 to 2029.

The following parameters are accepted:

=over

=item C<start> - The first date to retrieve data for (inclusive); Time::Moment object or RFC3339 string

=item C<end> - The last date to retrieve data for (inclusive); Time::Moment object or RFC3339 string

=back

lib/Finance/Alpaca.pm  view on Meta::CPAN

Both listed parameters are optional. If neither is provided, the calendar will
begin on January 1st, 1970.

=head2 C<assets( [...] )>

    say $_->symbol
        for sort { $a->symbol cmp $b->symbol } @{ $camelid->assets( status => 'active' ) };

Returns a list of L<Finance::Alpaca::Struct::Asset> objects.

The assets endpoint serves as the master list of assets available for trade and
data consumption from Alpaca.

The following parameters are accepted:

=over

=item C<status> - e.g. C<active> or C<inactive>. By default, all statuses are included

=item C<asset_class> - Defaults to C<us_equity>

lib/Finance/Alpaca.pm  view on Meta::CPAN

  my %bars = $camelid->bars(
        symbol    => 'MSFT',
        timeframe => '1Min',
        start     => Time::Moment->now->with_hour(10),
        end       => Time::Moment->now->minus_minutes(20)
    );

Returns a list of L<Finance::Alpaca::Struct::Bar> objects along with other
data.

The bar endpoint serves aggregate historical data for the requested securities.

The following parameters are accepted:

=over

=item C<symbol> - The symbol to query for; this is required

=item C<start> - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required

=item C<end> - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required

lib/Finance/Alpaca.pm  view on Meta::CPAN


    my %quotes = $camelid->quotes(
        symbol => 'MSFT',
        start  => Time::Moment->now->with_hour(10),
        end    => Time::Moment->now->minus_minutes(20)
    );

Returns a list of L<Finance::Alpaca::Struct::Quote> objects along with other
data.

The bar endpoint serves quote (NBBO) historical data for the requested
security.

The following parameters are accepted:

=over

=item C<symbol> - The symbol to query for; this is required

=item C<start> - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required

lib/Finance/Alpaca.pm  view on Meta::CPAN


    my %trades = $camelid->trades(
        symbol => 'MSFT',
        start  => Time::Moment->now->with_hour(10),
        end    => Time::Moment->now->minus_minutes(20)
    );

Returns a list of L<Finance::Alpaca::Struct::Trade> objects along with other
data.

The bar endpoint serves historical trade data for a given ticker symbol on a
specified date.

The following parameters are accepted:

=over

=item C<symbol> - The symbol to query for; this is required

=item C<start> - Filter data equal to or before this time in RFC-3339 format or a Time::Moment object. Fractions of a second are not accepted; this is required

lib/Finance/Alpaca.pm  view on Meta::CPAN


This method expects a code reference. This callback will receive all incoming
data.

=head2 C<orders( [...] )>

    my @orders = $camelid->orders( status => 'open' );

Returns a list of L<Finance::Alpaca::Struct::Order> objects.

The orders endpoint returns a list of orders for the account, filtered by the
supplied parameters.

The following parameters are accepted:

=over

=item C<status> - Order status to be queried. C<open>, C<closed>, or C<all>. Defaults to C<open>.

=item C<limit> - The maximum number of orders in response. Defaults to C<50> and max is C<500>.

lib/Finance/Alpaca/Cookbook.pod  view on Meta::CPAN

You can see various information about your account, such as the amount of
buying power available or whether or not it has a L<PDT
flag|https://forum.alpaca.markets/t/general-trading/2339>.

    my $account = $alpaca->account;
    print 'Account is currently restricted from trading. ' if $account->trading_blocked;
    printf '$%f is available as buying power', $account->buying_power;

=head2 View Gain/Loss of Portfolio

You can use the information from the account endpoint to do things like
calculating the daily profit or loss of your account.

    my $account        = $alpaca->account;
    my $balance_change = $account->equity - $account->last_equity;
    printf q[Today's portfolio balance change: $%.4f], $balance_change;

=head1 Assets Examples

Listed instruments can be gathered en mass or individually.

lib/Finance/Alpaca/Struct/Activity.pm  view on Meta::CPAN

    use Finance::Alpaca;
    for my $activity (Finance::Alpaca->new( ... )->activities( activity_types => [qw[ACATC ACATS]] )) {
        say sprintf '%s @ %f', $activity->symbol, $activity->net_amount
    }

=head1 DESCRIPTION

The account activities API provides access to a historical record of
transaction activities that have impacted your account. Trade execution
activities and non-trade activities, such as dividend payments, are both
reported through this endpoint. See the bottom of this page for a full list of
the types of activities that may be reported.

=head1 Properties

The following properties are contained in the object.

    for my $activity ($camelia->activities()) {
        say $activity->symbol;
    }

lib/Finance/Alpaca/Struct/Calendar.pm  view on Meta::CPAN

        start => Time::Moment->now,
        end   => Time::Moment->now->plus_days(14)
    );
    for my $day (@days) {
        say sprintf '%s the market opens at %s Eastern',
            $day->date, $day->open;
    }

=head1 DESCRIPTION

The calendar endpoint serves the full list of market days from 1970 to 2029. It
can also be queried by specifying a start and/or end time to narrow down the
results. In addition to the dates, the response also contains the specific open
and close times for the market days, taking into account early closures.

=head1 Properties

A calendar day contains the following properties:

    $day->date();

lib/Finance/Alpaca/Struct/Clock.pm  view on Meta::CPAN


=head1 SYNOPSIS

    use Finance::Alpaca;
    my $clock = Finance::Alpaca->new( ... )->clock;
    say sprintf $clock->timestamp->strftime('It is %l:%M:%S %p on a %A and the market is %%sopen!'),
           $clock->is_open ? '' : 'not ';

=head1 DESCRIPTION

The clock endpoint serves the current market timestamp, whether or not the
market is currently open, as well as the times of the next market open and
close.

=head1 Properties

The following properties are contained in the object.

    $clock->is_open( );

=over

lib/Finance/Alpaca/Struct/TradeActivity.pm  view on Meta::CPAN

=head1 SYNOPSIS

    use Finance::Alpaca;
    my @activities = Finance::Alpaca->new( ... )->activities;

=head1 DESCRIPTION

The account activities API provides access to a historical record of
transaction activities that have impacted your account. Trade execution
activities and non-trade activities, such as dividend payments, are both
reported through this endpoint. See the bottom of this page for a full list of
the types of activities that may be reported.

=head1 Properties

The following properties are contained in the object.

    for my $activity ($camelia->activities()) {
        say $activity->symbol;
    }



( run in 1.680 second using v1.01-cache-2.11-cpan-2b1a40005be )