@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
-
schema
Joi A Joi schema for the model -
props
object 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
-
shouldPrettify
boolean 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
-
props
object 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
-
props
object 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
-
schema
Joi The model schema -
props
object 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
-
id
string The unique id for the user's broker account (this is usually the unique user id received from the broker) -
exchanges_enabled
Array<string> All the exchanges that are enabled for the user by this broker -
products_enabled
Array<string> All the products that are enabled for the user by this broker -
balance
object? The balance available in the user's broker account-
balance.equity
Object<Broker.BalanceSchema>? The balance available for equity, futures & options trading Broker.BalanceSchema -
balance.commodity
Object<Broker.BalanceSchema>? The balance available for commodity trading Broker.BalanceSchema
-
Broker.BalanceSchema
BalanceSchema
Type: Joi
Parameters
-
used
number? Positive values denote the amount blocked into a Open order or position. Negative value denotes the amount being released. -
span
number? Amount blocked on futures and options towards SPAN -
adhoc
number? Payin amount credited through a manual process -
available
number? Total margin available for trading -
exposure
number? Amount blocked on futures and options towards Exposure -
payin_amount
number? Instant payin will reflect here -
notional_cash
number? The amount maintained for withdrawal
Broker.HoldingSchema
HoldingSchema
Type: Joi
Parameters
-
instrument_id
string The unique id for the instrument -
product
string Shows if the order was either Intraday, Delivery, CO or OCO -
quantity
number The total holding quantity -
t1_quantity
number? Quantity on T+1 day after order execution. Stocks are usually delivered into DEMAT accounts on T+2 -
cnc_used_quantity
number? Quantity either blocked towards open or completed order -
collateral_type
number? Category of collateral assigned by RMS -
haircut
number? This is the haircut percentage applied from RMS (applicable in case of collateral) -
avg_price
number? 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_id
string The unique id for the instrument -
product
string Shows if the order was either Intraday, Delivery, CO or OCO -
intraday
object? The positions held during the day -
carry_forward
object? The positions carried forward from previous day -
pnl
object? The profit or loss
CorporateAction
CorporateAction model class
Type: module.CorporateAction
CorporateAction.Schema
CorporateActionSchema
Type: Joi
Parameters
-
id
string The unique id of the instrument
Instrument
Instrument model class
Type: module.Instrument
Instrument.Schema
InstrumentSchema
Type: Joi
Parameters
-
id
string The unique id for the instrument -
exchange
string The exchange the instrument belongs to -
symbol
string The symbol of the instrument -
exchange_token
string The unique token of the instrument at exchange level -
isin
string? The unique isin value of the instrument -
tick_size
number? The tick size of the instrument -
strike_price
number? The strike price of the instrument in case of an option -
lot_size
number? The lot size of the instrument in case of a future/option -
expiry
number? The expiry timestamp of the instrument in case of a future/option -
is_enabled
boolean? Whether the instrument is enabled or not (Defaults totrue
) -
sector
string? The sector to which the instrument belongs
News
News model class
Type: module.News
News.Schema
NewsSchema
Type: Joi
Parameters
-
id
string The unique id of the instrument
Ohlc
Ohlc model class
Type: module.Ohlc
Ohlc.Schema
OhlcSchema
Type: Joi
Parameters
-
id
string The unique id for the instrument -
timestamp
number The timestamp when the tick was last updated -
open
number The open price of the instrument -
high
number The high price of the instrument -
low
number The low price of the instrument -
close
number The close price of the instrument -
volume
number? The volume of the instrument that was transacted at last tick
Strategy
Strategy model class
Type: module.Strategy
Strategy.Schema
StrategySchema
Type: Joi
Parameters
-
id
string The unique id of the strategy
Tick.Schema
TickSchema
Type: Joi
Parameters
-
timestamp
number The timestamp when the tick was last updated -
price
number The price of the instrument for bid or ask -
size
number The size or quantity of the instrument for bid or ask
Tick.Schema
TickSchema
Type: Joi
Parameters
-
id
string The unique id for the tick, should correspond to the unique instrument id -
last_timestamp
number? The timestamp when the tick was last updated -
last_price
number? The last price of the instrument -
last_size
number? The last contract size that was transacted -
avg_price
number? The average price of instrument at the given time -
tbq
number? The total buy quantities of the instrument -
tsq
number? The total sell quantities of the instrument -
ohlc
Object<Ohlc.Schema>? The OHLC data point for the instrument at the given time Ohlc.Schema -
oi
number? The open interest standing at the given time -
oi_day_high
number? The day's high value of open interest for the instrument -
oi_day_low
number? The day's low value of open interest for the instrument -
bids
Array<Tick.DepthSchema>? The bid side of the depth of book for the instrument Tick.DepthSchema -
asks
Array<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
-
role
string 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
-
props
object 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
-
id
string The unique user id for this Auth -
token
string The unique access token for this Auth -
email
string? The email address for this Auth -
profile
object? The user's profile details -
broker_details
object? 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
-
id
string The unique user id for this Auth -
created_at
number The unix timestamp when the object was created (in milliseconds) -
updated_at
number The unix timestamp when the object was updated (in milliseconds) -
emails
array A list of emails and whether it is verified or not -
password
string The password for user login -
roles
array The list of User.UserRole -
check
object? Various type of boolean checks-
check.is_verified
boolean? Whether the user is verified or not -
check.is_suspended
boolean? Whether the user is suspended or not -
check.is_deleted
boolean? Whether the user is deleted or not -
check.suspension_reason
string? The reason for user's account suspension User.AccountSuspensionReason
-
-
first_name
string? The user's first name -
last_name
string? The user's last name -
avatar_url
string? The user's avatar URL -
auth
object? The user's other auth objects-
auth.google
object? The Google oauth details User.AuthSchema -
auth.facebook
object? The Facebook oauth details User.AuthSchema -
auth.upstox
object? The Upstox broker oauth details User.AuthSchema -
auth.zerodha
object? 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_ROLE
string The Super Admin Role -
ADMIN_ROLE
string The Admin Role -
USER_ROLE
string The normal User Role
User.AccountSuspensionReason
Various reasons for account suspension
Type: object