npm package: @qfin/schemas
Description: The awesome database schemas for QFin
Author: Quantofin
Latest version: 0.0.31


<h1 align="center">
  <p align="center">@qfin/schemas</p>
  <p align="center" style="font-size: 0.5em">The awesome database schemas for QFin</p>
</h1><br />
<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source files, and re-run
./build/generate-docs.js from the project root. -->
---

> The awesome database schemas for QFin 😎 ❤

## 📦 Features

- Support for [ES6 modules](http://exploringjs.com/es6/ch_modules.html)
- Unit testing using [Jest](https://jestjs.io)
- All the usual goodies: [ESLint](https://eslint.org/), [Babel](https://babeljs.io/), [Webpack](https://webpack.js.org) etc.
- Auto code formatting using [Prettier](https://prettier.io/)
- Automated versioning
- Automated [changelog](../CHANGELOG.md) generator
- Automated [readme](../README.md) file and source documentation generator
- Git Hooks integrations - `git push` will trigger auto build, versioning, documentation generation etc.
- Watch for file changes in development mode
- Local in-memory DynamoDB database support

## 💾 Install

**Latest Release:** @qfin/schemas:0.0.31

```bash
npm install @qfin/schemas
```

## 💻 Development

Most of the things are automated so as a developer you will have less things to worry or care about. _Simply write code and let us take care of the rest._

### Running

#### Development Mode

You can run the development mode of the application by simply running the following command:

```bash
npm run dev
```

This will trigger a `development` build and the build system will skip testing, generating documentations etc. thereby reducing the build time significantly.

Once the build is completed, the application will start in development mode.

**NOTE:**
In `development` mode only, the system will watch for file changes. Any further changes to the source files will trigger a rebuild and will restart the application automatically and also the local database.

#### Production Mode

The production mode of the application can be started as follows:

```bash
npm run prod
```

This will trigger a `production` build and will do all the relevant automation of testing, generating documentations etc.

Once the build process is completed, the application will start in production mode. _Changes to the filesystem will not be watched under this mode._

### Testing

Tests will be automatically run when you do `git push`.

Test files should end with `.spec.js` filename and should be kept in a `__tests__/` directory under respective places as a good convention.

You can always manually run the test as follows:

```bash
npm run test
```

### Building

The project will be automatically built when you do `git push`.

Production build may take a couple of minutes as several steps are involved in the process such as running test coverage, generating documentations, building docker image etc.

Ideally you dont need to build the project manually unless you are testing the build system itself.

```bash
npm run build
```

## 🔗 Git

### Git Commit

All `git commit` messages will be logged in the CHANGELOG file automatically. Hence it is advisable to commit your code often with small changes and give meaningful commit message.

Try to follow [git flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow) branching model.

The seven rules of a great Git commit message (adapted from [here](https://chris.beams.io/posts/git-commit/)):

- Separate subject from body with a blank line
- Limit the subject line to 50 characters
- Capitalize the subject line
- Do not end the subject line with a period
- Use the imperative mood in the subject line
- Wrap the body at 72 characters
- Use the body to explain what and why vs. how

### Git Push

Doing `git push` will trigger the git-hooks which will do a bunch of stuffs for you automatically: 

- Increment the patch version of the project
- Trigger a production build
- Running tests
- Generating project documentations
- Update CHANGELOG with all git commits until the point of last push
- Update the README file
- Update the version in docker-compose.yml file
- Generating new versioned docker image

**NOTE:** If you wish to skip these automations, then you should do `git push --no-verify`.
One usecase would be to skip incrementing the package version when merging two branches and pushing the merged code.

## ⚙ QFin Schemas Documentation


<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## PurposeType

`@qfin/schemas` defines various object schemas and corresponding helper methods that can be used to do CRUD operations across DynamoDB databases.

Type: [object][1]

### Examples

```javascript
const Schemas = require('@qfin/schemas');
// OR
import Schemas from '@qfin/schemas';

const {Announcement, Instrument, Ohlc, User} = Schemas;
```

## Model.formatDynamooseResults

This is the general format of the returned results from the model query or scan methods.

Type: [object][1]

### Parameters

-   `items` **[array][2]&lt;Model.instance>** The array containing the found model instances
-   `count` **[number][3]** The total number of items retured after filtering
-   `scanned` **[number][3]** The total number of items scanned before filtering
-   `timesQueried` **[number][3]?** The total number times the items were queried
-   `lastKey` **[object][1]?** The last key used for pagination

## Model.createNew

Create a new model object
Every new model instance will have a unique random id which will be autogenerated if absent from the props.

**NOTE:**

All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `props` **[object][1]?** The model object properties based on the model's schema

Returns **[Promise][5]&lt;Model.instance>** A promise containing the newly created model object

## Model.scanWithFilter

Scan a given model with a given set of filter object

**NOTE:**

All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `filter` **([object][1] \| [undefined][6])** The filter object [https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html][7]
    -   `filter.FilterExpression` **[object][1]** The filter expression as par DynamoDB documentations
    -   `filter.ExpressionAttributeValues` **[object][1]** The filter attribute values as par DynamoDB documentations
-   `props` **[object][1]** The scan properties
    -   `props.offset` **[object][1]?** The last key offset
    -   `props.limit` **[number][3]** The number of documents to return. Defaults to 100 (optional, default `100`)
    -   `props.attributes` **[Array][2]&lt;[string][8]>?** The attributes to return from this scan

### Examples

```javascript
const { items, lastKey} = await Schema.scanWithFilter({
   FilterExpression: filterExpression,
   ExpressionAttributeValues: attributeValues,
});
```

Returns **[Promise][5]&lt;[Model.formatDynamooseResults][9]>** A promise containing the model result [Model.formatDynamooseResults][10]

## Model.scanWithFilterExpression

Scan a given model with a given set of filter expression and value

**NOTE:**

All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `filterExpression` **[string][8]** The filter expression as par DynamoDB documentations
-   `attributeValues` **[string][8]** The filter attribute values as par DynamoDB documentations
-   `props` **[object][1]?** The optional scan properties
    -   `props.offset` **[object][1]?** The last key offset
    -   `props.limit` **[number][3]** The number of documents to return. Defaults to 100 (optional, default `100`)
    -   `props.attributes` **[Array][2]&lt;[string][8]>?** The attributes to return from this scan

### Examples

```javascript
const { items, lastKey} = await Schema.scanWithFilterExpression(`${key} = :prop`, { ':prop': value });
```

Returns **[Promise][5]&lt;[Model.formatDynamooseResults][9]>** A promise containing the model result [Model.formatDynamooseResults][10]

## Model.scanWithKeyValue

Scan a given model with a given set of key-value condition. Match will look for equality.

**NOTE:**

All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `key` **[string][8]** The key to filter by
-   `value` **any** The value to search for. This will be matched exactly (full and case senstive)
-   `props` **[object][1]?** The optional scan properties
    -   `props.offset` **[object][1]?** The last key offset
    -   `props.limit` **[number][3]** The number of documents to return. Defaults to 100 (optional, default `100`)
    -   `props.attributes` **[Array][2]&lt;[string][8]>?** The attributes to return from this scan

### Examples

```javascript
const { items, lastKey} = await Schema.scanWithKeyValue('xyz', 10);
```

Returns **[Promise][5]&lt;[Model.formatDynamooseResults][9]>** A promise containing the model result [Model.formatDynamooseResults][10]

## Model.scanAll

Scan a given model to find all instances in a paginated way.

**NOTE:**

All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `props` **[object][1]?** The optional scan properties
    -   `props.offset` **[object][1]?** The last key offset
    -   `props.limit` **[number][3]** The number of documents to return. Defaults to 100 (optional, default `100`)
    -   `props.attributes` **[Array][2]&lt;[string][8]>?** The attributes to return from this scan

Returns **[Promise][5]&lt;[Model.formatDynamooseResults][9]>** A promise containing the model result [Model.formatDynamooseResults][10]

## Model.findByIndex

Queries a given model to search by a global index.

**NOTE:**

All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `query` **[object][1]** The query object
-   `index` **[string][8]** The name of the global index to use
-   `props` **[object][1]?** The optional properties
    -   `props.offset` **[object][1]?** The last key offset for paginatiopn
    -   `props.limit` **[number][3]** The number of documents to return. Defaults to 100. (optional, default `100`)
    -   `props.attributes` **[Array][2]&lt;[string][8]>?** The attributes to return from this scan
    -   `props.sort` **[number][3]** Sort the data. Positive sorts in ascending order, negative in descending. (optional, default `-1`)

Returns **[Promise][5]&lt;[Model.formatDynamooseResults][9]>** A promise containing the model result [Model.formatDynamooseResults][10]

## Model.insance.get

Get the property value of a model instance using string dot path. [https://github.com/aheckmann/mpath][11]

**NOTE:**

This is an insance level method.
All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `path` **[string][8]** The dot separated property path

Returns **any** The value of the property

## Model.insance.set

Set the property value of a model instance using string dot path. [https://github.com/aheckmann/mpath][11]
The model is NOT saved at this point, you need to handle saving to database separately by calling the `save` method.

**NOTE:**

This is an insance level method.
All models implements this method and can have its unique behavior. Check model specific documentation for more details (if any).

Type: [function][4]

### Parameters

-   `path` **[string][8]** The dot separated property path
-   `value` **any** The value to set for the property

Returns **void** 

## CorporateAction.Schema

Schema of CorporateAction

Type: [object][1]

### Parameters

-   `id` **[Number][3]** The unique id
-   `timestamp` **[Number][3]** The timestamp of the ohlc point
-   `purpose` **[Number][3]** 
-   `exDate` **[Number][3]** The date at which a stock will trade "cum ex" (without entitlement).
    So for example in a normal cash dividend, if the exdate is 25.11.2008 then the stock will trade without the right
    to the cash dividendfrom the 25.11.2008 onwards. Cum (latin for with) and Ex (latin for without).
-   `recordDate` **[Number][3]** The date at which your positions will be recorded in order to calculate your entitlements.
    So for example; if the positions in your account on record date are 100,000 shares and a cash dividend pays EUR 0.25 per share
    then your entitlement will be calculated as 100,000 x EUR 0.25 = EUR 25,000.
-   `bcStartDate` **[Number][3]** Book closure is a time period during which a company will not handle adjustments to the register, or requests to transfer shares. Companies will often use the book closure date to identify the cut-off date for determining which investors of record will receive a particular dividend payment.
-   `bcEndDate` **[Number][3]** Book closure end date
-   `ndStartDate` **[Number][3]** 
-   `ndEndDate` **[Number][3]** 

### Examples

```javascript
const corporateAction = {
  "id": 123456,
  "timestamp": 1554651528383,
  "purpose": CorporateAction.PurposeType.AGM,
};
```

## CorporateAction.PurposeType

The available exchnage values

Type: [object][1]

### Parameters

-   `AGM` **[Number][3]** Annual General Meeting Announcement
-   `BOND` **[Number][3]** Bond Announcement
-   `BONUS` **[Number][3]** Bonus Announcement
-   `BUYBACK` **[Number][3]** Buy Back Announcement
-   `FIRST_CALL` **[Number][3]** First Call Announcement
-   `DIVIDEND` **[Number][3]** Dividend Announcement
-   `INT_DIVIDEND` **[Number][3]** Interim Dividend Announcement
-   `DISTRIBUTION` **[Number][3]** Distribution Announcement
-   `INTEREST_PAYMENT` **[Number][3]** Interest Payment Announcement
-   `REDEMPTION` **[Number][3]** Redemption Announcement
-   `STOCK_SPLIT` **[Number][3]** Stock Split Announcement
-   `CONSOLIDATION` **[Number][3]** A reverse stock split is a type of corporate action which consolidates
    the number of existing shares of stock into fewer, proportionally more valuable, shares.
    The process involves a company reducing the total number of its outstanding shares in the open market,
    and often signals a company in distress.

## CorporateAction.PurposeType.fromString

Convert string value to InstrumentType value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as AGM, DIVIDEND etc.

Returns **[Number][3]** The PurposeType value {@see CorporateAction.PurposeType}

## Instrument.generateId

Generate instrument id out of exchange and symbol

Type: [function][4]

### Parameters

-   `props` **[object][1]** The properties used to generate the unique id
    -   `props.country` **[number][3]** The country code for this instrument [Instrument.Country][12]
    -   `props.exchange` **[number][3]** The exchange id for this instrument [Instrument.Exchange][13]
    -   `props.symbol` **[string][8]** The symbol for this instrument
    -   `props.series` **[string][8]** The series this instrument belongs to

### Examples

```javascript
const id = Instrument.generateId({
  country: Instrument.Country.INDIA,
  exchange: Instrument.Exchange.INDIA_NSE,
  series: 'EQ',
  symbol: 'RELIANCE',
});
```

Returns **[number][3]** The generated unique id for this instrument

## Instrument.createNew

Create a new instrument
Every new instrument will have a unique id which will be autogenerated based on the exchnage and symbol fields

Type: [function][4]

### Parameters

-   `props` **[object][1]** The instrument object properties based on [Instrument.Schema][14]

### Examples

```javascript
const instrument = await Instrument.createNew({
  // id: 3371985954, auto-generated constant id for this isntrument
  country: Instrument.Country.INDIA,
  exchange: Instrument.Exchange.INDIA_NSE,
  instrumentType: Instrument.InstrumentType.EQ,
  series: 'EQ',
  symbol: 'RELIANCE',
  name: 'Reliance Industries Limited',
  exchangeId: '2885',
  brokerId: {
    zerodha: 1012012,
    upstox: '2885',
  },
});
```

Returns **[Promise][5]&lt;Instrument.instance>** A promise containing the newly created instrument

## Instrument.getAllContracts

Get all contracts

Type: [function][4]

### Parameters

-   `country` **[number][3]** The country for which all contracts are needed (optional, default `Instrument.Country.INDIA`)

Returns **[Promise][5]&lt;[Array][2]&lt;Instrument.instance>>** A promise containing the contracts array

## Instrument.getAllContractsCopy

Get all the contracts data from AWS S3 copy

Type: [function][4]

### Parameters

-   `s3` **[object][1]** The AWS S3 instance
-   `bucket` **[string][8]?** The upload bucket. Defaults to `${process.env.NODE_ENV || 'production'}.data.quantofin.com`
-   `key` **[string][8]?** The upload file key. Defaults to `contracts.json`

Returns **[Promise][5]&lt;[Object][1]>** Contracts data

## Instrument.saveAllContractsCopy

Save a copy of all the contracts as file to AWS S3

Type: [function][4]

### Parameters

-   `s3` **[object][1]** The AWS S3 instance
-   `data` **([string][8] \| [Buffer][15])** The json data to upload
-   `bucket` **[string][8]?** The upload bucket. Defaults to `${process.env.NODE_ENV || 'production'}.data.quantofin.com`
-   `key` **[string][8]?** The upload file key. Defaults to `contracts.json`

Returns **[Promise][5]&lt;[Object][1]>** AWS S3 promise object

## Instrument.deleteContracts

Delete the contract file from AWS S3

Type: [function][4]

### Parameters

-   `s3` **[object][1]** The AWS S3 instance
-   `bucket` **[string][8]?** The upload bucket. Defaults to `${process.env.NODE_ENV || 'production'}.data.quantofin.com`
-   `key` **[string][8]?** The upload file key. Defaults to `contracts.json`

Returns **[Promise][5]&lt;[Object][1]>** AWS S3 promise object

## Instrument.Country

The available Countries

Type: [object][1]

### Parameters

-   `INDIA` **[Number][3]** India: 1
-   `USA` **[Number][3]** United States of America: 2

## Instrument.Country.fromString

Convert string value to Country value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as INDIA, IND etc.

Returns **[Number][3]** The Country value {@see Instrument.Country}

## Instrument.Exchange

The available Exchnages

Type: [object][1]

### Parameters

-   `INDIA_NSE` **[Number][3]** NSE India: 101
-   `INDIA_BSE` **[Number][3]** BSE India: 102
-   `INDIA_MCX` **[Number][3]** MCX India: 103

## Instrument.Exchange.fromString

Convert string value to Exchange value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as NSE, BSE, MCX etc.

Returns **[Number][3]** The Exchange value {@see Instrument.Exchange}

## Instrument.InstrumentType

The available exchnage values

Type: [object][1]

### Parameters

-   `INDEX` **[Number][3]** Index Type: 10
-   `INDEX_FUTURE` **[Number][3]** Index Future Type: 11
-   `EQ` **[Number][3]** Equity Type: 20
-   `EQ_FUTURE` **[Number][3]** Equity Fture Type: 21
-   `OPTION_CE` **[Number][3]** European Call Option Type: 31
-   `OPTION_PE` **[Number][3]** European Put Option Type: 32

## Instrument.InstrumentType.fromString

Convert string value to InstrumentType value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as EQ, FUT, CE, PE etc.

Returns **[Number][3]** The InstrumentType value {@see Instrument.InstrumentType}

## Instrument.Schema

Schema of Instrument

Type: [object][1]

### Parameters

-   `id` **[number][3]** The unique instrument id for this instrument. This is autogenerated based on the exchnage and symbol fields
-   `country` **[number][3]** The country code to which this instrument belongs
-   `exchange` **[number][3]** The exchange type [Instrument.Exchange][13]
-   `instrumentType` **[number][3]** The instrument type [Instrument.InstrumentType][16]
-   `symbol` **[string][8]** The symbol for the instrument - unit across a given exchange
-   `series` **[string][8]** The series this instrument belongs to. For example: NSE has EQ, BE etc. series
-   `name` **[string][8]** The name of the instrument
-   `exchangeId` **[string][8]** The unique token provided by the Exchnage for this instrument
-   `brokerId` **[object][1]** The unique token provided by the given broker for this instrument
    -   `brokerId.zerodha` **[string][8]** The unique token provided by Zerodha broker for this instrument
    -   `brokerId.upstox` **[string][8]** The unique token provided by Upstox broker for this instrument
    -   `brokerId.bloomberg` **[string][8]** The unique token provided by Bloomberg broker for this instrument
-   `circuit` **[object][1]** The upper and lower circuit limits for this instrument
    -   `circuit.upper` **[string][8]** The upper circuit band
    -   `circuit.lower` **[string][8]** The lower circuit band
-   `isDeleted` **[boolean][17]?** Whether or not the instrument is deleted from the Exchnage
-   `isEnabled` **[boolean][17]?** Whether or not the instrument is enabled in the Exchnage
-   `isTradeable` **[boolean][17]?** Whether or not the instrument is tradeable in the Exchnage. For eg. Indices are not tradeable in India, but there Future contracts are
-   `isin` **[string][8]?** The unique ISIN value for the instrument
-   `faceValue` **[number][3]?** The face value of the instrument
-   `issuedCapital` **[number][3]?** The issued capital of the instrument
-   `strikePrice` **[number][3]?** The strike price in case the instrument is an Option contract
-   `tickSize` **[number][3]?** The minimum size move allowed for this instrument
-   `lotSize` **[number][3]?** The minimum amount of quantity and its multiple allowed for trading. This is relevant to Future & Option contracts
-   `expiry` **[number][3]?** The expiry timestamp for the instrument contract
-   `sector` **[object][1]?** The sectoral information this instrument belongs to
    -   `sector.name` **[string][8]?** The name of the sector
    -   `sector.subSector` **[string][8]?** The type of subsector (if any)
-   `yearly` **[object][1]?** The yearly extremeties of the stock
    -   `yearly.high` **[string][8]?** Yearly high
        -   `yearly.high.value` **[string][8]?** The yearly high price of the stock
        -   `yearly.high.date` **[string][8]?** The date when this high was achieved
    -   `yearly.low` **[string][8]?** Yearly low
        -   `yearly.low.value` **[string][8]?** The yearly low price of the stock
        -   `yearly.low.date` **[string][8]?** The date when this low was achieved
-   `openInterest` **[object][1]?** The open interest of the instrument
    -   `openInterest.value` **[string][8]?** The current open interest
    -   `openInterest.absoluteChange` **[string][8]?** The absolute change in open interest from previous day
-   `ohlc` **[object][1]?** The daily ohlc data points
    -   `ohlc.open` **[object][1]?** The current day's open price
    -   `ohlc.high` **[object][1]?** The current day's high
    -   `ohlc.low` **[object][1]?** The current day's low
    -   `ohlc.close` **[object][1]?** The current day's close
    -   `ohlc.lastTradedPrice` **[object][1]?** The current day's last price at which the intrument was traded
    -   `ohlc.previousClose` **[object][1]?** The previous day's close
    -   `ohlc.volume` **[object][1]?** The total traded volume or quantity traded
    -   `ohlc.trades` **[object][1]?** The trades related information
        -   `ohlc.trades.netValue` **[Number][3]?** The net value traded during the day
        -   `ohlc.trades.numberOfTrades` **[Number][3]?** The total number of trades for the dayinstrument

### Examples

```javascript
const instrument = {
  // id: 3371985954, auto-generated constant id for this isntrument
  country: Instrument.Country.INDIA,
  exchange: Instrument.Exchange.INDIA_NSE,
  instrumentType: Instrument.InstrumentType.EQ,
  series: Instrument.Series.EQ,
  symbol: 'RELIANCE',
  name: 'Reliance Industries Limited',
  exchangeId: '2885',
  brokerId: {
    zerodha: 1012012,
    upstox: '2885',
  },
};
```

## Ohlc.getCandles

Get all candles for a given instrument and period

Type: module.Ohlc.getCandles

### Parameters

-   `id` **[number][3]** The instrument id
-   `period` **[number][3]** The period of candle [Ohlc.Period][18] (optional, default `Ohlc.Period.DAILY`)
-   `offset` **[object][1]?** The last key offset
-   `limit` **[number][3]** The number of documents to return. Defaults to 100 (optional, default `100`)
-   `sort` **[number][3]** Sort the data. Positive sorts in ascending order, negative in descending. (optional, default `-1`)

### Examples

```javascript
const candles = await Model.getCandles(123456, {
  period: Model.Period.INTRADAY_1_MIN,
  start: Date.now() - 9000000,
  limit: 200,
  sort: 1,
});
```

Returns **[Promise][5]&lt;[Model.formatDynamooseResults][9]>** A promise containing the model result [Model.formatDynamooseResults][10]

## Ohlc.Period

The available ohlc periods

Type: module.Ohlc.Period

### Parameters

-   `INTRADAY_1_MIN` **[Number][3]** Intraday 1 minute candles: 1
-   `INTRADAY_5_MIN` **[Number][3]** Intraday 5 minutes candles: 5
-   `INTRADAY_10_MIN` **[Number][3]** Intraday 10 minutes candles: 10
-   `INTRADAY_15_MIN` **[Number][3]** Intraday 15 minutes candles: 15
-   `INTRADAY_30_MIN` **[Number][3]** Intraday 30 minutes candles: 30
-   `INTRADAY_60_MIN` **[Number][3]** Intraday 60 minutes candles: 60
-   `DAILY` **[Number][3]** Daily candles: 101

## Ohlc.Period.fromString

Convert string value to Period value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as DAILY, 1_MIN, 30_MIN etc.

Returns **[Number][3]** The Period value {@see Ohlc.Period}

## Ohlc.Schema

Schema of Ohlc Canlde Data

Type: [object][1]

### Parameters

-   `id` **[Number][3]** The unique id
-   `timestamp` **[Number][3]** The timestamp of the ohlc point
-   `period` **[Number][3]** The period of the ohlc candle [Ohlc.Period][18]
-   `open` **[Number][3]** The open value of the candle
-   `high` **[Number][3]** The high value of the candle
-   `low` **[Number][3]** The low value of the candle
-   `close` **[Number][3]** The close value of the candle
-   `lastTradedPrice` **[Number][3]?** The last traded price of the instrument
-   `previousClose` **[Number][3]?** The close value for the previous day
-   `volume` **[Number][3]?** The volume traded
-   `trades` **[object][1]?** The trades related information
    -   `trades.netValue` **[Number][3]?** The net value traded during the day
    -   `trades.numberOfTrades` **[Number][3]?** The total number of trades for the day
-   `adjusted` **[object][1]?** The adjusted values
    -   `adjusted.open` **[Number][3]?** The adjusted open value
    -   `adjusted.high` **[Number][3]?** The adjusted high value
    -   `adjusted.low` **[Number][3]?** The adjusted low value
    -   `adjusted.close` **[Number][3]?** The adjusted close value

### Examples

```javascript
const ohlc = {
  "id": 123456,
  "timestamp": 1554651528383,
  "open": 627.52,
  "high": 627.52,
  "low": 621.83,
  "close": 622.98,
};
```

## User.createNew

Create a new user
Every new user will have a unique random id and a unique referral.id and these will be autogenerated if absent from the props.
NOTE: If a password field is present, it will be treated as plain text and will be auto encrypted before creating the user.

Type: [function][4]

### Parameters

-   `props` **[object][1]** The user object properties based on [User.Schema][19]

### Examples

```javascript
const userProps = {
    email: 'user@email.com',
    password: 'Password@123',
    roles: [ 'user' ],
    referral: {
      id: 'ABCD',
    },
    profile: {
      firstname: 'First',
      lastname: 'Last',
      avatarUrl: 'https://avatar.auth.url',
    }
};

await User.createNew(userProps);
```

Returns **[Promise][5]&lt;User.instance>** A promise containing the newly created user

## User.findOneByEmail

Search a user by her email address.
NOTE: The provided email must be an exact case-insensitive match. This can't match against partial email address.

Type: [function][4]

### Parameters

-   `email` **[string][8]** The user's email address

### Examples

```javascript
await User.findOneByEmail('user@email.com');
```

Returns **[Promise][5]&lt;User.instance>** A promise containing the found user

## User.findOneByOAuthId

Search a user by her OAuth provider and id.
NOTE: This is a scan and not a query hence will be slow and is not recommended to call often

Type: [function][4]

### Parameters

-   `provider` **[string][8]** The provider - google, facebook, upstox, zerodha
-   `id` **[string][8]** The user's id as given by the provider

### Examples

```javascript
await User.findOneByOAuthId('google', 'G-1234');
```

Returns **[Promise][5]&lt;User.instance>** A promise containing the found user

## User.instance.hasRole

Check if the user has a given role or not
NOTE: This is an instance method

Type: [function][4]

### Parameters

-   `role` **[number][3]** The role to check [User.Roles][20]

### Examples

```javascript
user.hasRole(User.Roles.ADMIN);
```

Returns **[boolean][17]** Whether or not the user has the given role

## User.instance.isValidPassword

Check if the given plain text password matches with the user's encrypted password
NOTE: This is an instance method

Type: [function][4]

### Parameters

-   `password` **[string][8]** The password to check as plain text

### Examples

```javascript
user.isValidPassword('abcd');
```

Returns **[boolean][17]** Whether or not the given password matches against the user's set password

## User.AccountSuspensionReason

Various reasons for account suspension

Type: [object][1]

### Parameters

-   `LICENSE_EXPIRED` **[string][8]** Due to license expiry
-   `USER_BLOCKED` **[string][8]** Because the user is blocked by Admin
-   `IP_BLOCKED` **[string][8]** Because the user's IP is blocked by Admin

## User.Role

A map of available User Roles

Type: [object][1]

### Parameters

-   `SUPER_ADMIN` **[number][3]** The super admin role
-   `ADMIN` **[number][3]** The admin role
-   `PARTNER` **[number][3]** The partner role
-   `PREMIUM_USER` **[number][3]** The premium user role
-   `USER` **[number][3]** The user role. Everyone gets this role

## User.Role.fromString

Convert string value to Role value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as admin, user etc.

Returns **[Number][3]** The Role value {@see User.Role}

## User.AuthSchema

AuthSchema of User
Generally this schema is used for OAuth authorization and login

Type: module.User.AuthSchema

### Parameters

-   `id` **[string][8]** The unique user id for this Auth
-   `token` **[string][8]** The unique access token for this Auth
-   `email` **[string][8]?** The email address for this Auth
-   `profile` **[object][1]?** The user's profile details
    -   `profile.firstname` **[string][8]?** The user's first name
    -   `profile.lastname` **[string][8]?** The user's last name
    -   `profile.phone` **[string][8]?** The user's phone number
    -   `profile.avatarUrl` **[string][8]?** The user's avatar URL

### Examples

```javascript
const auth = {
    id: 'ABC123',
    token: 'someuniqueauthtoken',
    email: 'user@email.com',
    profile: {
        avatarUrl: 'https://avatar.auth.url',
        firstname: 'First',
        lastname: 'Last',
        phone: '+911234567890',
    }
};
```

## User.Schema

Schema of User

Type: module.User.Schema

### Parameters

-   `id` **[number][3]** The unique user id for this Auth (Auto generated if absent)
-   `createdAt` **[number][3]** The unix timestamp when the object was created (in milliseconds)
-   `updatedAt` **[number][3]** The unix timestamp when the object was updated (in milliseconds)
-   `email` **[string][8]** The user's primary email
-   `roles` **[array][2]** The list of [User.Role][21]
-   `password` **[string][8]?** The password for user login - atleast 1 lowercase, 1 uppercase, 1 number, 1 special ch. and must be 8 or more chars
-   `referral` **[object][1]** User's referral details
    -   `referral.id` **[string][8]** User's referral id (Auto generated if absent)
    -   `referral.referredBy` **[number][3]?** User's referree's user id
    -   `referral.referredUsers` **[array][2]?** The user ids of the referred users
-   `profile` **[object][1]?** The user profile
    -   `profile.firstname` **[string][8]?** The user's first name
    -   `profile.lastname` **[string][8]?** The user's last name
    -   `profile.avatarUrl` **[string][8]?** The user's avatar URL
    -   `profile.phone` **[string][8]?** The user's phone number
-   `auth` **[object][1]?** The user's other auth objects
    -   `auth.google` **[object][1]?** The Google oauth details [User.AuthSchema][22]
    -   `auth.facebook` **[object][1]?** The Facebook oauth details [User.AuthSchema][22]
    -   `auth.upstox` **[object][1]?** The Upstox broker oauth details [User.AuthSchema][22]
    -   `auth.zerodha` **[object][1]?** The Zerodha broker oauth details [User.AuthSchema][22]
-   `payment` **[object][1]?** The user's payment information
    -   `payment.firstPaymentDate` **[date][23]?** The user's first payment date
    -   `payment.paymentDate` **[date][23]?** The user's last payment date
    -   `payment.expiryDate` **[date][23]?** The user's payment expiry date
    -   `payment.plan` **[string][8]?** The user's payment plan
    -   `payment.license` **[string][8]?** The user's payment licence code
-   `subscription` **[object][1]?** The user's various subscription details
    -   `subscription.email` **[boolean][17]?** Whether the user has enabled email notification or not
    -   `subscription.pushNotification` **[boolean][17]?** Whether the user has enabled push notification or not
-   `check` **[object][1]?** Various type of boolean checks
    -   `check.isVerified` **[boolean][17]?** Whether the user is verified or not
    -   `check.isSuspended` **[boolean][17]?** Whether the user is suspended or not
    -   `check.isDeleted` **[boolean][17]?** Whether the user is deleted or not
    -   `check.suspensionReason` **[string][8]?** The reason for user's account suspension [User.AccountSuspensionReason][24]

### Examples

```javascript
const user = {
    id: 123,
    email: 'user@email.com',
    password: 'Password@123',
    roles: [User.Role.USER],
    referral: {
      id: 'ABCD',
    },
    auth: {
      google: {#User.AuthSchema}
    },
    profile: {
      firstname: 'First',
      lastname: 'Last',
      avatarUrl: 'https://avatar.auth.url',
    }
};
```

## Scanner.Name

The available Scanners

Type: [object][1]

### Parameters

-   `OPEN_EQUALS_HIGH` **[Number][3]** : 1001
-   `OPEN_EQUALS_LOW` **[Number][3]** : 1002
-   `GAINERS_AND_LOSERS` **[Number][3]** : 1003
-   `OPEN_RANGE_BREAKOUT` **[Number][3]** : 1004
-   `OVER_BOUGHT_AND_SOLD` **[Number][3]** : 1005
-   `GAP_UP_AND_DOWN` **[Number][3]** : 1006
-   `CARAMILLA_POINTS` **[Number][3]** : 1007

## Scanner.Name.fromString

Convert string value to Scanner Name value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as OPEN_EQUALS_HIGH, GAINERS_AND_LOSERS, OVER_BOUGHT_AND_SOLD etc.

Returns **[Number][3]** The Scanner Name value {@see Scanner.Name}

## Scanner.Type

The available Scanner Types

Type: [object][1]

### Parameters

-   `FEED` **[Number][3]** : 1
-   `CANDLE` **[Number][3]** : 2

## Scanner.Type.fromString

Convert string value to Scanner Type value

Type: [function][4]

### Parameters

-   `val` **[String][8]** The string value such as FEED, CANDLE etc.

Returns **[Number][3]** The Scanner Type value {@see Scanner.Type}

## Scanner.Schema

Schema of Scanner Data

Type: [Object][1]

### Parameters

-   `name` **[Number][3]** The name of the scanner [Scanner.Name][25]
-   `type` **[Number][3]** The type of the scanner [Scanner.Type][26]
-   `data` **[Object][1]** The computed data of the scanner

### Examples

```javascript
const scanner = {
  "name": 1001,
  "scannerType": 1,
  "data": {
     "instruments": [3371985954]
  },
};
```

[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object

[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array

[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number

[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function

[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise

[6]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined

[7]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html

[8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

[9]: #modelformatdynamooseresults

[10]: #modelformatdynamooseresults

[11]: https://github.com/aheckmann/mpath

[12]: #instrumentcountry

[13]: #instrumentexchange

[14]: #instrumentschema

[15]: https://nodejs.org/api/buffer.html

[16]: #instrumentinstrumenttype

[17]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean

[18]: #ohlcperiod

[19]: #userschema

[20]: User.Roles

[21]: #userrole

[22]: #userauthschema

[23]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date

[24]: #useraccountsuspensionreason

[25]: #scannername

[26]: #scannertype