alpaca-ts icon indicating copy to clipboard operation
alpaca-ts copied to clipboard

v7

Open 117 opened this issue 1 year ago • 52 comments

🦙 Alpaca Trading SDK v7 (work in progress)

[!NOTE]
Although this is a breaking change, the deprecated v6 will remain accessible through NPM if you are unable to make the necessary modifications to your code at this time.

Why v7?

I'm updating the Alpaca Trading SDK to include the latest endpoints for both crypto and stocks. To simplify future modifications, types have been consolidated alongside a reduction in the total number of files, lowering the overall code complexity.

Example

import { Client } from "@master-chief/alpaca-ts";

const client = new Client({
  paper: true,
  credentials: {
    key: "PK4Z802QBVAC6V4YMUV7",
    secret: "WEK6HzUjrtjTdVhvKhoQdp6DSn0ZujFOVhgUZkzZ",
  },
});

client.v2.getAccount().then((account) => {
  console.log(account);
});

Contributing

I hope that these updates will improve your overall experience with the Alpaca Trading SDK. If you have any feedback or suggestions, please let me know! Feel free to PR v7 branch.

117 avatar Apr 06 '23 17:04 117

I am excited

iukea1 avatar May 09 '23 18:05 iukea1

@iukea1 the endpoints are done i just need to do all the typings

117 avatar May 09 '23 18:05 117

@iukea1 the endpoints are done i just need to do all the typings

You are the man!

I am working on a NextJS project and I am excited to use the typescript equivalent of the Alpaca API

iukea1 avatar May 09 '23 18:05 iukea1

@iukea1 the endpoints are done i just need to do all the typings

By any chance did you get to work on this? I am just trying to figure out if I should use the other alpaca library for js.

Just I am trying to be a good boy and only use typescript (I am a noob when it comes to JS and typescript)

iukea1 avatar May 27 '23 05:05 iukea1

@iukea1 I wish I had the time, I keep trying but the days slip by. 😵‍💫 If you use v6 for now it's a small lift to switch over to v7. All of the types will have the same fields.

117 avatar May 30 '23 18:05 117

@117 Love what you are doing here.

Is there any chance to get the current state of v7 as a pre-alpha release so that I can paper trade cryptos while waiting for the work to progress?

DaviDevMod avatar Jul 24 '23 12:07 DaviDevMod

@DaviDevMod good idea! ill put in work on this today. pre-alpha would make this release easier

117 avatar Jul 24 '23 18:07 117

@DaviDevMod Hey! So no guarantee on typings being entirely accurate, however the REST endpoints should mostly all done. I setup an example here, the latest version is 7.0.2-alpha.

npm i @master-chief/[email protected]

I will work on streaming next. Please complain about any and everything you find. The more the better 😄

image

117 avatar Jul 24 '23 20:07 117

@117 Wow that was quick! Thank you so much.

I'll try to complain as much as possible :laughing:

It looks like my setup can't find type declarations for v7.0.2-alpha, I'll let you know what's the problem. For the moment I will only complain about a missing dist in the .gitignore.

Thank you again for the release! :tada:

DaviDevMod avatar Jul 24 '23 21:07 DaviDevMod

@117 Wow that was quick! Thank you so much.

I'll try to complain as much as possible 😆

It looks like my setup can't find type declarations for v7.0.2-alpha, I'll let you know what's the problem. For the moment I will only complain about a missing dist in the .gitignore.

Thank you again for the release! 🎉

odd they should be in "types": "./@types/index.d.ts",

117 avatar Jul 24 '23 21:07 117

sweeeeeeeeeeeeeeettt

iukea1 avatar Jul 24 '23 21:07 iukea1

generating the typings from openapi spec

117 avatar Jul 24 '23 22:07 117

generating the typings from openapi spec

Please forgive my ignorance, I never worked with openapi. Do you mean that having the typings in a "@typing" folder is an openapi standard?

https://github.com/alpacahq/alpaca-ts/blob/17410b983ea75566159b18d43ae5d72b00f806f7/tsconfig.json#L19

My setup can find the type declarations if they are generated alongside the .js files, but surely there must be a way to make that "declarationDir" work. I'll look into it when possible. By the way can you reproduce the issue or importing "@master-chief/alpaca-ts" with the v7.0.2-alpha just works for you?

DaviDevMod avatar Jul 24 '23 23:07 DaviDevMod

generating the typings from openapi spec

Please forgive my ignorance, I never worked with openapi. Do you mean that having the typings in a "@typing" folder is an openapi standard?

https://github.com/alpacahq/alpaca-ts/blob/17410b983ea75566159b18d43ae5d72b00f806f7/tsconfig.json#L19

My setup can find the type declarations if they are generated alongside the .js files, but surely there must be a way to make that "declarationDir" work. I'll look into it when possible. By the way can you reproduce the issue or importing "@master-chief/alpaca-ts" with the v7.0.2-alpha just works for you?

ill tag you in next release

image

im using generated classes and a custom client to interface with them. should all work out of the box

117 avatar Jul 24 '23 23:07 117

types are done. and good news. both stock and crypto market data endpoints will be included. i will finish the rest client probably tomorrow so its not quite usable yet. i think i should release it without a websocket client at first, it is an alpha anyways

i need to wrap this generated client into something more user friendly. with suggested endpoints, and credentials that match the alpaca docs

117 avatar Jul 25 '23 01:07 117

we're almost there 😬

117 avatar Jul 25 '23 01:07 117

@117 Really appreciate all the work you are putting in. Hope you manage to release without too many troubles :rocket:

I'm sure eventually you would notice that too, but there are a bunch of duplicate symbol identifiers in src/services/StockPricingDataApiService.ts.

https://github.com/alpacahq/alpaca-ts/blob/8a6dd61d35d0dc81fc41c4e5c4cd27f985fa3bfd/src/services/StockPricingDataApiService.ts#L316

You can get a list of them by trying to build the library :laughing:

DaviDevMod avatar Jul 25 '23 10:07 DaviDevMod

@117 Really appreciate all the work you are putting in. Hope you manage to release without too many troubles 🚀

I'm sure eventually you would notice that too, but there are a bunch of duplicate symbol identifiers in src/services/StockPricingDataApiService.ts.

https://github.com/alpacahq/alpaca-ts/blob/8a6dd61d35d0dc81fc41c4e5c4cd27f985fa3bfd/src/services/StockPricingDataApiService.ts#L316

You can get a list of them by trying to build the library 😆

Resolved that and did some refactoring to get it working. Below is what I have up on code sandbox: https://codesandbox.io/p/sandbox/xenodochial-framework-kf3ktz

import { OpenAPIClient } from "@master-chief/alpaca-ts";

const client = new OpenAPIClient({
  HEADERS: {
    "APCA-API-KEY-ID": "PK4Z802QBVAC6V4YMUV7",
    "APCA-API-SECRET-KEY": "WEK6HzUjrtjTdVhvKhoQdp6DSn0ZujFOVhgUZkzZ",
  },
});

client.account.service.getAccount().then(
  (account) => {
    console.log(account);
  },
  (err) => {
    console.error(err);
  }
);
{
  id: '840930b7-0771-43f0-9eb4-2b3db2fa7f24',
  admin_configurations: { Configurations: {} },
  user_configurations: null,
  account_number: 'PA3QAUAUE952',
  status: 'ACTIVE',
  crypto_status: 'ACTIVE',
  currency: 'USD',
  buying_power: '10299',
  regt_buying_power: '10299',
  daytrading_buying_power: '0',
  effective_buying_power: '10299',
  non_marginable_buying_power: '4921.57',
  bod_dtbp: '0',
  cash: '4921.57',
  accrued_fees: '0',
  pending_transfer_in: '0',
  portfolio_value: '5377.43',
  pattern_day_trader: false,
  trading_blocked: false,
  transfers_blocked: false,
  account_blocked: false,
  created_at: '2023-06-01T17:34:01.721563Z',
  trade_suspended_by_user: false,
  multiplier: '2',
  shorting_enabled: true,
  equity: '5377.43',
  last_equity: '5373.75',
  long_market_value: '455.86',
  short_market_value: '0',
  position_market_value: '455.86',
  initial_margin: '227.93',
  maintenance_margin: '136.758',
  last_maintenance_margin: '136.26',
  sma: '5373.75',
  daytrade_count: 0,
  balance_asof: '2023-07-24',
  crypto_tier: 1
}

That OpenAPI client and its options are temporary I'm refactoring that to make more sense. The version is 7.0.4-alpha.

117 avatar Jul 25 '23 17:07 117

@DaviDevMod

I've refactored the client. There may be some issues I don't know about yet, but let me know if this version works for you 😁! Most if not all the REST endpoints are there. There is no built in rate-limiting, ill add that next.

npm i @master-chief/[email protected]
import { Client } from "@master-chief/alpaca-ts";

const client = new Client({
  paper: true, // not necessary but just to show it's there by default
  credentials: {
    key: "PK4Z802QBVAC6V4YMUV7",
    secret: "WEK6HzUjrtjTdVhvKhoQdp6DSn0ZujFOVhgUZkzZ",
  },
});

client.account.getAccount().then((account) => {
  console.log(account);
});
image

117 avatar Jul 25 '23 18:07 117

@117 Looks great! :tada: The typings work and I am able to log my account.

However if I try to get crypto bars, I get 'endpoint not found.' It may be that there's something wrong in my request though. Here's my code:

await client.crypto.getBarsForCryptoSymbol({
  symbol: "ETH/BTC",
  start: "2023-07-22 00:00:00",
  end: "2023-07-23 00:00:00",
  timeframe: "1Hour",
});

And the error:

{
  url: 'https://paper-api.alpaca.markets/v1beta1/crypto/ETH/BTC/bars?start=2023-07-22%2000%3A00%3A00&end=2023-07-23%2000%3A00%3A00&timeframe=1Hour',
  status: 404,
  statusText: 'Not Found',
  body: { message: 'endpoint not found.' },
  request: {
    method: 'GET',
    url: '/v1beta1/crypto/{symbol}/bars',
    path: { symbol: 'ETH/BTC' },
    query: {
      start: '2023-07-22 00:00:00',
      end: '2023-07-23 00:00:00',
      timeframe: '1Hour',
      exchanges: undefined,
      limit: undefined,
      page_token: undefined
    }
  }
}

Note that I tried various date formats, like using a "T" "2023-07-22T00:00:00", or adding fractions of a second "2023-07-22 00:00:00+00:00:00" (though they are not supported), or omitting start and end altogether since they are optional parameters.

Any idea on why the endpoint is not found?

DaviDevMod avatar Jul 25 '23 19:07 DaviDevMod

@117 Looks great! 🎉 The typings work and I am able to log my account.

However if I try to get crypto bars, I get 'endpoint not found.' It may be that there's something wrong in my request though. Here's my code:

await client.crypto.getBarsForCryptoSymbol({
  symbol: "ETH/BTC",
  start: "2023-07-22 00:00:00",
  end: "2023-07-23 00:00:00",
  timeframe: "1Hour",
});

And the error:

{
  url: 'https://paper-api.alpaca.markets/v1beta1/crypto/ETH/BTC/bars?start=2023-07-22%2000%3A00%3A00&end=2023-07-23%2000%3A00%3A00&timeframe=1Hour',
  status: 404,
  statusText: 'Not Found',
  body: { message: 'endpoint not found.' },
  request: {
    method: 'GET',
    url: '/v1beta1/crypto/{symbol}/bars',
    path: { symbol: 'ETH/BTC' },
    query: {
      start: '2023-07-22 00:00:00',
      end: '2023-07-23 00:00:00',
      timeframe: '1Hour',
      exchanges: undefined,
      limit: undefined,
      page_token: undefined
    }
  }
}

Note that I tried various date formats, like using a "T" "2023-07-22T00:00:00", or adding fractions of a second "2023-07-22 00:00:00+00:00:00" (though they are not supported), or omitting start and end altogether since they are optional parameters.

Any idea on why the endpoint is not found?

Ah. It needs to be using data.alpaca.markets

117 avatar Jul 25 '23 20:07 117

@117 Looks great! 🎉 The typings work and I am able to log my account.

However if I try to get crypto bars, I get 'endpoint not found.' It may be that there's something wrong in my request though. Here's my code:

await client.crypto.getBarsForCryptoSymbol({
  symbol: "ETH/BTC",
  start: "2023-07-22 00:00:00",
  end: "2023-07-23 00:00:00",
  timeframe: "1Hour",
});

And the error:

{
  url: 'https://paper-api.alpaca.markets/v1beta1/crypto/ETH/BTC/bars?start=2023-07-22%2000%3A00%3A00&end=2023-07-23%2000%3A00%3A00&timeframe=1Hour',
  status: 404,
  statusText: 'Not Found',
  body: { message: 'endpoint not found.' },
  request: {
    method: 'GET',
    url: '/v1beta1/crypto/{symbol}/bars',
    path: { symbol: 'ETH/BTC' },
    query: {
      start: '2023-07-22 00:00:00',
      end: '2023-07-23 00:00:00',
      timeframe: '1Hour',
      exchanges: undefined,
      limit: undefined,
      page_token: undefined
    }
  }
}

Note that I tried various date formats, like using a "T" "2023-07-22T00:00:00", or adding fractions of a second "2023-07-22 00:00:00+00:00:00" (though they are not supported), or omitting start and end altogether since they are optional parameters.

Any idea on why the endpoint is not found?

Okay. Ive fixed the path for that endpoint in particular, try this on latest build:

client.crypto
  .getBarsForSymbol({
    symbols: "ETH/USD",
    start: "2023-07-22",
    end: "2023-07-23",
    timeframe: "1Min",
  })
  .then((data) => {
    console.log(data);
  });

The OpenAPI spec did not include v1beta3, v1beta2 was deprecated.

117 avatar Jul 25 '23 20:07 117

I'll fix all the other crypto endpoints.. 😢

117 avatar Jul 25 '23 20:07 117

They should be fixed.. let me know if you run into an issue. Going to refactor the method options as well, symbols as a prop for getBarsForSymbol makes no sense.

117 avatar Jul 25 '23 21:07 117

@117 Now the crypto endpoint works :partying_face: but I can't get my account anymore :grimacing:

I think that v7.0.6-alpha was the last one in which the account worked properly.

I put together a basic setup you can use to test your work the same way I do.

It's in the basic-setup branch of this repo: https://github.com/DaviDevMod/dabot

You can try stuff in index.ts. There's a "compile-n-run" script to run the file. There's also an "update-local-alpaca" script installing a local build of alpaca-ts (you'll probably need to tweak the path to your local tarball tough).

To use the local build, just npm run build && npm pack alpaca-ts, then in the basic setup npm run update-local-alpaca.

Obviously, you can always install a version from npmjs instead.

Hope it's going to help.

DaviDevMod avatar Jul 25 '23 23:07 DaviDevMod

Yeah i messed up, quickly fixing the data path before. I overwrote the account path.

        // change the baseURL to data.alpaca.markets
        this.httpRequest.config.BASE = "https://data.alpaca.markets";

needs to be done on a per request basis, changing the base url overwrites it

117 avatar Jul 26 '23 05:07 117

@DaviDevMod thanks for the repo. ill figure out a more robust solution for the multiple base urls needed

117 avatar Jul 26 '23 05:07 117

doing quite a bit of a refactor. might as well have written it from scratch lol. will tag you when i have it ready for testing. might be a few days

117 avatar Jul 26 '23 17:07 117

I just tried @master-chief/alpaca-ts v7.0.9-alpha with the example code provided:

import {Client} from '@master-chief/alpaca-ts';

const client = new Client({
  paper: true,
  credentials: {
    key: 'top-secret',
    secret: 'top-secret',
  },
});

client.account.getAccount().then((account) => {
  console.log(account);
});

When running the example it returns the following error:

ApiError: Not Found

{
  "body": {
    "message": "endpoint not found."
  },
  "request": {
    "method": "GET",
    "url": "/v2/account"
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "https://data.alpaca.markets/v2/account"
}

From what I understood, the base URL must be https://paper-api.alpaca.markets instead of https://data.alpaca.markets/ when paper is set to true, no?

bennycode avatar Aug 06 '23 12:08 bennycode

back to this now. ill tag you when ready

117 avatar Aug 07 '23 17:08 117