Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
117 committed Jul 26, 2023
1 parent 8d79a67 commit e8ed811
Show file tree
Hide file tree
Showing 19 changed files with 407 additions and 385 deletions.
76 changes: 19 additions & 57 deletions src/Client.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,8 @@
import type { BaseHttpRequest } from "./rest/BaseHttpRequest";
import type { ApiRequestOptions } from "./rest/ApiRequestOptions";

import account from "./api/account";
import { AxiosHttpRequest } from "./rest/AxiosHttpRequest";
import { Logos } from "./paths/logos";
import { News } from "./paths/news";
import { Clock } from "./paths/clock";
import { Orders } from "./paths/orders";
import { Assets } from "./paths/assets";
import { AccountService } from "./paths/AccountService.js";
import { Calendar } from "./paths/calendar";
import { Crypto } from "./paths/crypto";
import { Stocks } from "./paths/stocks";
import { Screener } from "./paths/screener";
import { Positions } from "./paths/positions";
import { Watchlists } from "./paths/watchlists";
import { Account } from "./paths/account";
import { PortfolioHistoryService } from "./paths/PortfolioHistoryService.js";
import { AccountConfigurations } from "./paths/AccountConfigurations";
import { prewrap } from "./rest/prewrap";

type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
type Headers = Record<string, string>;
Expand All @@ -41,45 +27,18 @@ interface ClientOptions {
};
}

// bundle all account services into one class for convenience
class AccountServices extends AccountService {
activities: Account;
configurations: AccountConfigurations;
positions: Positions;
orders: Orders;
portfolioHistory: PortfolioHistoryService;

constructor(httpRequest: BaseHttpRequest) {
super(httpRequest);
this.activities = new Account(httpRequest);
this.configurations = new AccountConfigurations(httpRequest);
this.positions = new Positions(httpRequest);
this.orders = new Orders(httpRequest);
this.portfolioHistory = new PortfolioHistoryService(httpRequest);
}
}

export class Client {
private readonly request: BaseHttpRequest;

public readonly calendar: Calendar;
public readonly clock: Clock;
public readonly assets: Assets;
public readonly crypto: Crypto;
public readonly logo: Logos;
public readonly news: News;
public readonly screener: Screener;
public readonly stocks: Stocks;
public readonly watchlists: Watchlists;
public readonly account: AccountServices;
private readonly baseHttpRequest: BaseHttpRequest;

constructor(
options?: ClientOptions,
HttpRequest: HttpRequestConstructor = AxiosHttpRequest
) {
const { paper, credentials } = options ?? {};

this.request = new HttpRequest({
// base request object for all requests
// changes based on paper/live mode and/or data endpoints
this.baseHttpRequest = new HttpRequest({
BASE:
paper === true || paper === undefined
? "https://paper-api.alpaca.markets"
Expand All @@ -91,16 +50,19 @@ export class Client {
}
: undefined,
});
}

get account() {
return prewrap(account, this.baseHttpRequest.config);
}

this.account = new AccountServices(this.request);
this.watchlists = new Watchlists(this.request);
this.calendar = new Calendar(this.request);
this.clock = new Clock(this.request);
this.assets = new Assets(this.request);
this.crypto = new Crypto(this.request);
this.logo = new Logos(this.request);
this.news = new News(this.request);
this.screener = new Screener(this.request);
this.stocks = new Stocks(this.request);
get assets() {
return prewrap(assets, this.baseHttpRequest.config);
}
}

const client = new Client();

client.account.get().then((account) => {
console.log(account);
});
208 changes: 208 additions & 0 deletions src/api/account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import type {
Account,
NonTradeActivities,
TradingActivities,
CancelablePromise,
BaseHttpRequest,
AccountConfigurations,
PortfolioHistory,
} from "../";

const activities = {
/**
* Get account activities of one type
* Returns account activity entries for many types of activities.
* @returns any returns an array of Account activities
* @throws ApiError
*/
get: (
httpRequest: BaseHttpRequest,
{
activityTypes,
}: {
/**
* A comma-separated list of the activity types to include in the response. If unspecified, activities of all types will be returned. (Cannot be used with category)
*/
activityTypes?: "trade_activity" | "non_trade_activity";
}
): CancelablePromise<Array<TradingActivities | NonTradeActivities>> => {
return httpRequest.request({
method: "GET",
url: "/v2/account/activities",
query: {
activity_types: activityTypes,
},
});
},
/**
* Get account activities of one type
* Returns account activity entries for a specific type of activity.
* @returns any returns an array of Account activities
* @throws ApiError
*/
getByType: (
httpRequest: BaseHttpRequest,
{
activityType,
date,
until,
after,
direction,
pageSize,
pageToken,
category,
}: {
/**
* The activity type you want to view entries for. A list of valid activity types can be found at the bottom of this page.
*/
activityType: string;
/**
* The date for which you want to see activities.
*/
date?: string;
/**
* The response will contain only activities submitted before this date. (Cannot be used with date.)
*/
until?: string;
/**
* The response will contain only activities submitted after this date. (Cannot be used with date.)
*/
after?: string;
/**
* asc or desc (default desc if unspecified.)
*/
direction?: "asc" | "desc";
/**
* The maximum number of entries to return in the response. (See the section on paging above.)
*/
pageSize?: number;
/**
* The ID of the end of your current page of results.
*/
pageToken?: string;
/**
* trade_activity or non_trade_activity, to specify the kind of results the server should return. (Cannot be used with /{activity_type} or ?activity_types=...)
*/
category?: string;
}
): CancelablePromise<Array<TradingActivities | NonTradeActivities>> => {
return httpRequest.request({
method: "GET",
url: "/v2/account/activities/{activity_type}",
path: {
activity_type: activityType,
},
query: {
date: date,
until: until,
after: after,
direction: direction,
page_size: pageSize,
page_token: pageToken,
category: category,
},
});
},
};

/**
* Get account
* Returns the account associated with the API key.
* @returns Account OK
* @throws ApiError
*/
function get(httpRequest: BaseHttpRequest): CancelablePromise<Account> {
return httpRequest.request({
method: "GET",
url: "/v2/account",
});
}

/**
* Account Portfolio History
* Returns timeseries data about equity and profit/loss (P/L) of the account in requested timespan.
* @returns PortfolioHistory Successful response
* @throws ApiError
*/
function portfolioHistory(
httpRequest: BaseHttpRequest,
{
period,
timeframe,
dateEnd,
extendedHours,
}: {
/**
* The duration of the data in <number> + <unit>, such as 1D, where <unit> can be D for day, W for week, M for month and A for year. Defaults to 1M.
*/
period?: string;
/**
* The resolution of time window. 1Min, 5Min, 15Min, 1H, or 1D. If omitted, 1Min for less than 7 days period, 15Min for less than 30 days, or otherwise 1D.
*/
timeframe?: string;
/**
* The date the data is returned up to, in “YYYY-MM-DD” format. Defaults to the current market date (rolls over at the market open if extended_hours is false, otherwise at 7am ET)
*/
dateEnd?: string;
/**
* If true, include extended hours in the result. This is effective only for timeframe less than 1D.
*/
extendedHours?: string;
}
): CancelablePromise<PortfolioHistory> {
return httpRequest.request({
method: "GET",
url: "/v2/account/portfolio/history",
query: {
period: period,
timeframe: timeframe,
date_end: dateEnd,
extended_hours: extendedHours,
},
});
}

const config = {
/**
* Account Configurations
* gets the current account configuration values
* @returns AccountConfigurations Successful response
* @throws ApiError
*/
get: (
httpRequest: BaseHttpRequest
): CancelablePromise<AccountConfigurations> => {
return httpRequest.request({
method: "GET",
url: "/v2/account/configurations",
});
},
/**
* Account Configurations
* Updates and returns the current account configuration values
* @returns AccountConfigurations Successful response
* @throws ApiError
*/
patch: (
httpRequest: BaseHttpRequest,
{
requestBody,
}: {
requestBody?: AccountConfigurations;
}
): CancelablePromise<AccountConfigurations> => {
return httpRequest.request({
method: "PATCH",
url: "/v2/account/configurations",
body: requestBody,
mediaType: "application/json",
});
},
};

export default {
get,
config,
activities,
portfolioHistory,
};
85 changes: 85 additions & 0 deletions src/api/assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import type { Assets } from "../entities/Assets.js";
import type { CancelablePromise } from "../rest/CancelablePromise";
import { BaseHttpRequest } from "../rest/BaseHttpRequest";

/**
* Get Assets
* The assets API serves as the master list of assets available for trade and data consumption from Alpaca. Assets are sorted by asset class, exchange and symbol.
* @returns Assets An array of asset objects
* @throws ApiError
*/
function get(
httpRequest: BaseHttpRequest,
{
status,
assetClass,
exchange,
attributes,
}: {
/**
* e.g. “active”. By default, all statuses are included.
*/
status?: string;
/**
* Defaults to us_equity.
*/
assetClass?: string;
/**
* Optional AMEX, ARCA, BATS, NYSE, NASDAQ, NYSEARCA or OTC
*/
exchange?: string;
/**
* Comma separated values to query for more than one attribute.
*/
attributes?: string;
}
): CancelablePromise<Array<Assets>> {
return httpRequest.request({
method: "GET",
url: "/v2/assets",
query: {
status: status,
asset_class: assetClass,
exchange: exchange,
attributes: attributes,
},
});
}

/**
* Get an Asset by ID or Symbol
* Get the asset model for a given symbol or asset_id. The symbol or asset_id should be passed in as a path parameter.
*
* **Note**: For crypto, the symbol has to follow old symbology, e.g. BTCUSD.
*
* **Note**: For coin pairs, the symbol should be separated by spare symbol (/), e.g. BTC/USDT. Since spare is a special character in HTTP, use the URL encoded version instead, e.g. /v2/assets/BTC%2FUSDT
* @returns Assets An Asset object
* @throws ApiError
*/
function getBySymbolOrAssetId(
httpRequest: BaseHttpRequest,
{
symbolOrAssetId,
}: {
/**
* symbol or assetId
*/
symbolOrAssetId: string;
}
): CancelablePromise<Assets> {
return httpRequest.request({
method: "GET",
url: "/v2/assets/{symbol_or_asset_id}",
path: {
symbol_or_asset_id: symbolOrAssetId,
},
errors: {
404: `Not Found`,
},
});
}

export default {
get,
getBySymbolOrAssetId,
};
Loading

0 comments on commit e8ed811

Please sign in to comment.