@qfin/schema
v0.7.0
Published
The awesome repor for Quantofin schemas
Downloads
2
Readme
@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 protected]' }],
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 modelprops
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 schemaprops
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 brokerproducts_enabled
Array<string> All the products that are enabled for the user by this brokerbalance
object? The balance available in the user's broker accountbalance.equity
Object<Broker.BalanceSchema>? The balance available for equity, futures & options trading Broker.BalanceSchemabalance.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 SPANadhoc
number? Payin amount credited through a manual processavailable
number? Total margin available for tradingexposure
number? Amount blocked on futures and options towards Exposurepayin_amount
number? Instant payin will reflect herenotional_cash
number? The amount maintained for withdrawal
Broker.HoldingSchema
HoldingSchema
Type: Joi
Parameters
instrument_id
string The unique id for the instrumentproduct
string Shows if the order was either Intraday, Delivery, CO or OCOquantity
number The total holding quantityt1_quantity
number? Quantity on T+1 day after order execution. Stocks are usually delivered into DEMAT accounts on T+2cnc_used_quantity
number? Quantity either blocked towards open or completed ordercollateral_type
number? Category of collateral assigned by RMShaircut
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 instrumentproduct
string Shows if the order was either Intraday, Delivery, CO or OCOintraday
object? The positions held during the daycarry_forward
object? The positions carried forward from previous daypnl
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 instrumentexchange
string The exchange the instrument belongs tosymbol
string The symbol of the instrumentexchange_token
string The unique token of the instrument at exchange levelisin
string? The unique isin value of the instrumenttick_size
number? The tick size of the instrumentstrike_price
number? The strike price of the instrument in case of an optionlot_size
number? The lot size of the instrument in case of a future/optionexpiry
number? The expiry timestamp of the instrument in case of a future/optionis_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 instrumenttimestamp
number The timestamp when the tick was last updatedopen
number The open price of the instrumenthigh
number The high price of the instrumentlow
number The low price of the instrumentclose
number The close price of the instrumentvolume
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 updatedprice
number The price of the instrument for bid or asksize
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 idlast_timestamp
number? The timestamp when the tick was last updatedlast_price
number? The last price of the instrumentlast_size
number? The last contract size that was transactedavg_price
number? The average price of instrument at the given timetbq
number? The total buy quantities of the instrumenttsq
number? The total sell quantities of the instrumentohlc
Object<Ohlc.Schema>? The OHLC data point for the instrument at the given time Ohlc.Schemaoi
number? The open interest standing at the given timeoi_day_high
number? The day's high value of open interest for the instrumentoi_day_low
number? The day's low value of open interest for the instrumentbids
Array<Tick.DepthSchema>? The bid side of the depth of book for the instrument Tick.DepthSchemaasks
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 Authtoken
string The unique access token for this Authemail
string? The email address for this Authprofile
object? The user's profile detailsbroker_details
object? Additional user's details if the Auth is of Broker Auth type
Examples
const auth = {
id: 'ABC123',
token: 'someuniqueauthtoken',
email: '[email protected]',
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 Authcreated_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 notpassword
string The password for user loginroles
array The list of User.UserRolecheck
object? Various type of boolean checkscheck.is_verified
boolean? Whether the user is verified or notcheck.is_suspended
boolean? Whether the user is suspended or notcheck.is_deleted
boolean? Whether the user is deleted or notcheck.suspension_reason
string? The reason for user's account suspension User.AccountSuspensionReason
first_name
string? The user's first namelast_name
string? The user's last nameavatar_url
string? The user's avatar URLauth
object? The user's other auth objectsauth.google
object? The Google oauth details User.AuthSchemaauth.facebook
object? The Facebook oauth details User.AuthSchemaauth.upstox
object? The Upstox broker oauth details User.AuthSchemaauth.zerodha
object? The Zerodha broker oauth details User.AuthSchema
Examples
const user = {
id: 'ABC123',
emails: [
{ email: '[email protected]', 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 RoleADMIN_ROLE
string The Admin RoleUSER_ROLE
string The normal User Role
User.AccountSuspensionReason
Various reasons for account suspension
Type: object