@qfin/schema v0.7.0
@qfin/schema
This module is part of the Quantofin project.
The awesome @qfin/schema for Quantofin apps ❤
💾 Install
npm install --save @qfin/schema⚙ Module documentation
index
Remember to always validate the model before saving to database or sending over the wire.
Examples
const { User } = require('@qfin/schema');
const user = new User({
emails: [{ email: 'email@test.com' }],
roles: [User.UserRole.ADMIN_ROLE],
});
await user.validate({
phones: [{ phone: '+9100000000', is_verified: true }],
});
//
// Support for Protocol Buffers:
//
// You can efficiently serialize/deserialize the data object to protocol buffers as follows
// By default all long 64bit integer values are forced to long.js formats
// Hence you will need to `npm install long` to support that
const UserProto = User.proto.User;
// encode
const encodedBuffer = UserProto.encode(UserProto.fromObject(user.props)).finish();
// decode
const userObject = UserProto.toObject(UserProto.decode(encodedBuffer));Model
This is an abstract class which should be extended by all models
Type: module.Model
Parameters
schemaJoi A Joi schema for the modelpropsobject The model object properties
Examples
const {Model} = require('@qfin/schema');
const UserSchema = require('./userSchema');
class User extends Model {
constructor(props) {
super(UserSchema, props);
}
}getSchema
Gets the model schema reference
Returns Model
getProps
Gets the model properties as copy
Returns object Copy of the model props
toJSON
Formats the model props to json string
Parameters
shouldPrettifyboolean Whether to prettify the json string (optional, defaultfalse)
Returns string The JSON string of the model
validate
Validate the given properties with the model schema. The given properties will be appended to the existing props and overwrite if any
Parameters
propsobject The new properties
Returns Promise<?> Resolves with the model instance or rejects with an error
update
Validates the properties and then saves the model by calling Model#save()
Parameters
propsobject The new props to validate and update
Returns Promise<(Model | Error)> Resolves with the saved model instance or rejects with an error
save
Abstract method, must be implemented by the child class
Returns Promise<(Model | Error)> Resolves with the saved model instance or rejects with an error
findAll
Abstract method, must be implemented by the child class
Parameters
props
Returns Promise<(Model | Error)> Resolves with the saved model instance or rejects with an error
findOne
Abstract method, must be implemented by the child class
Parameters
props
Returns Promise<(Model | Error)> Resolves with the saved model instance or rejects with an error
delete
Abstract method, must be implemented by the child class
Returns Promise<(Model | Error)> Resolves with the saved model instance or rejects with an error
validate
Validate the properties against the schema definition
Parameters
schemaJoi The model schemapropsobject The model properties to validate
Returns Promise<(Joi | Error)> Resolves to the validated model properties or rejects with an error
Broker
Broker model class
Type: module.Broker
Broker.Schema
BrokerSchema
Type: Joi
Parameters
idstring The unique id for the user's broker account (this is usually the unique user id received from the broker)exchanges_enabledArray<string> All the exchanges that are enabled for the user by this brokerproducts_enabledArray<string> All the products that are enabled for the user by this brokerbalanceobject? The balance available in the user's broker accountbalance.equityObject<Broker.BalanceSchema>? The balance available for equity, futures & options trading Broker.BalanceSchemabalance.commodityObject<Broker.BalanceSchema>? The balance available for commodity trading Broker.BalanceSchema
Broker.BalanceSchema
BalanceSchema
Type: Joi
Parameters
usednumber? Positive values denote the amount blocked into a Open order or position. Negative value denotes the amount being released.spannumber? Amount blocked on futures and options towards SPANadhocnumber? Payin amount credited through a manual processavailablenumber? Total margin available for tradingexposurenumber? Amount blocked on futures and options towards Exposurepayin_amountnumber? Instant payin will reflect herenotional_cashnumber? The amount maintained for withdrawal
Broker.HoldingSchema
HoldingSchema
Type: Joi
Parameters
instrument_idstring The unique id for the instrumentproductstring Shows if the order was either Intraday, Delivery, CO or OCOquantitynumber The total holding quantityt1_quantitynumber? Quantity on T+1 day after order execution. Stocks are usually delivered into DEMAT accounts on T+2cnc_used_quantitynumber? Quantity either blocked towards open or completed ordercollateral_typenumber? Category of collateral assigned by RMShaircutnumber? This is the haircut percentage applied from RMS (applicable in case of collateral)avg_pricenumber? It indicates the consolidated price across all the orders placed for the scrip. Note: Corporate actions are not taken into consideration
Broker.PositionSchema
PositionSchema
Type: Joi
Parameters
instrument_idstring The unique id for the instrumentproductstring Shows if the order was either Intraday, Delivery, CO or OCOintradayobject? The positions held during the daycarry_forwardobject? The positions carried forward from previous daypnlobject? The profit or loss
CorporateAction
CorporateAction model class
Type: module.CorporateAction
CorporateAction.Schema
CorporateActionSchema
Type: Joi
Parameters
idstring The unique id of the instrument
Instrument
Instrument model class
Type: module.Instrument
Instrument.Schema
InstrumentSchema
Type: Joi
Parameters
idstring The unique id for the instrumentexchangestring The exchange the instrument belongs tosymbolstring The symbol of the instrumentexchange_tokenstring The unique token of the instrument at exchange levelisinstring? The unique isin value of the instrumenttick_sizenumber? The tick size of the instrumentstrike_pricenumber? The strike price of the instrument in case of an optionlot_sizenumber? The lot size of the instrument in case of a future/optionexpirynumber? The expiry timestamp of the instrument in case of a future/optionis_enabledboolean? Whether the instrument is enabled or not (Defaults totrue)sectorstring? The sector to which the instrument belongs
News
News model class
Type: module.News
News.Schema
NewsSchema
Type: Joi
Parameters
idstring The unique id of the instrument
Ohlc
Ohlc model class
Type: module.Ohlc
Ohlc.Schema
OhlcSchema
Type: Joi
Parameters
idstring The unique id for the instrumenttimestampnumber The timestamp when the tick was last updatedopennumber The open price of the instrumenthighnumber The high price of the instrumentlownumber The low price of the instrumentclosenumber The close price of the instrumentvolumenumber? The volume of the instrument that was transacted at last tick
Strategy
Strategy model class
Type: module.Strategy
Strategy.Schema
StrategySchema
Type: Joi
Parameters
idstring The unique id of the strategy
Tick.Schema
TickSchema
Type: Joi
Parameters
timestampnumber The timestamp when the tick was last updatedpricenumber The price of the instrument for bid or asksizenumber The size or quantity of the instrument for bid or ask
Tick.Schema
TickSchema
Type: Joi
Parameters
idstring The unique id for the tick, should correspond to the unique instrument idlast_timestampnumber? The timestamp when the tick was last updatedlast_pricenumber? The last price of the instrumentlast_sizenumber? The last contract size that was transactedavg_pricenumber? The average price of instrument at the given timetbqnumber? The total buy quantities of the instrumenttsqnumber? The total sell quantities of the instrumentohlcObject<Ohlc.Schema>? The OHLC data point for the instrument at the given time Ohlc.Schemaoinumber? The open interest standing at the given timeoi_day_highnumber? The day's high value of open interest for the instrumentoi_day_lownumber? The day's low value of open interest for the instrumentbidsArray<Tick.DepthSchema>? The bid side of the depth of book for the instrument Tick.DepthSchemaasksArray<Tick.DepthSchema>? The ask side of the depth of book for the instrument Tick.DepthSchema
User
User model class
Type: module.User
Examples
const {User} = require('@qfin/schema');
const user = new User({
})hasRole
Check if the user has a given role
Parameters
rolestring The role to check
Returns boolean true if role is present
validate
Validates the props and if valid returns the user object with updated props
Parameters
propsobject The user properties (optional, default{})
Returns Promise<(User | Error)> Promise resolves with user data or error
User.AuthSchema
AuthSchema of User Generally this schema is used for OAuth authorization and login
Type: Joi
Parameters
idstring The unique user id for this Authtokenstring The unique access token for this Authemailstring? The email address for this Authprofileobject? The user's profile detailsbroker_detailsobject? Additional user's details if the Auth is of Broker Auth type
Examples
const auth = {
id: 'ABC123',
token: 'someuniqueauthtoken',
email: 'user@email.com',
profile: {
first_name: 'First',
last_name: 'Last',
phone: '+911234567890',
avatar_url: 'https://avatar.auth.url',
}
};User.Schema
Schema of User
Type: Joi
Parameters
idstring The unique user id for this Authcreated_atnumber The unix timestamp when the object was created (in milliseconds)updated_atnumber The unix timestamp when the object was updated (in milliseconds)emailsarray A list of emails and whether it is verified or notpasswordstring The password for user loginrolesarray The list of User.UserRolecheckobject? Various type of boolean checkscheck.is_verifiedboolean? Whether the user is verified or notcheck.is_suspendedboolean? Whether the user is suspended or notcheck.is_deletedboolean? Whether the user is deleted or notcheck.suspension_reasonstring? The reason for user's account suspension User.AccountSuspensionReason
first_namestring? The user's first namelast_namestring? The user's last nameavatar_urlstring? The user's avatar URLauthobject? The user's other auth objectsauth.googleobject? The Google oauth details User.AuthSchemaauth.facebookobject? The Facebook oauth details User.AuthSchemaauth.upstoxobject? The Upstox broker oauth details User.AuthSchemaauth.zerodhaobject? The Zerodha broker oauth details User.AuthSchema
Examples
const user = {
id: 'ABC123',
emails: [
{ email: 'user@email.com', is_verified: true },
],
phones: [
{ phone: '+911234567890' },
],
password: 'Password@123',
roles: [ 'USER_ROLE' ],
first_name: 'First',
last_name: 'Last',
avatar_url: 'https://avatar.auth.url',
auth: {
google: {#User.AuthSchema}
}
};User.UserRole
A map of available User Roles
Type: module.User.UserRole
Parameters
SUPER_ADMIN_ROLEstring The Super Admin RoleADMIN_ROLEstring The Admin RoleUSER_ROLEstring The normal User Role
User.AccountSuspensionReason
Various reasons for account suspension
Type: object