Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/enable godmode req #36

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions components/lib/ExpiryTypeComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React from 'react'
import {
FormControl,
FormControlLabel,
Typography,
FormLabel,
RadioGroup,
Radio,
Grid
} from '@material-ui/core'
import { EXPIRY_TYPE, EXPIRY_TYPE_HUMAN } from '../../lib/constants'

const ExpiryTypeComponent = ({ state, onChange }) => {
const expiryTypes = [
EXPIRY_TYPE.CURRENT,
EXPIRY_TYPE.NEXT,
EXPIRY_TYPE.MONTHLY
]
return (
<Grid item xs={12}>
<FormControl component='fieldset'>
<FormLabel component='legend'>Option Expiry</FormLabel>
<RadioGroup
aria-label='expiryTypes'
name='expiryType'
value={state.expiryType}
onChange={e =>
onChange({ expiryType: e.target.value as EXPIRY_TYPE })
}
row
>
{expiryTypes.map(expiryType => (
<FormControlLabel
key={expiryType}
value={expiryType}
control={<Radio size='small' />}
label={
<Typography variant='body2'>
{EXPIRY_TYPE_HUMAN[expiryType]}
</Typography>
}
/>
))}
</RadioGroup>
</FormControl>
</Grid>
)
}

export default ExpiryTypeComponent
5 changes: 4 additions & 1 deletion components/lib/commonDetailsRows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ const CommonDetailsRows = ({
volatilityType,
liveTrailingSl,
lastTrailingSlSetAt,
lastHeartbeatAt
lastHeartbeatAt,
expiryType
}) => {
const getAlgoStatus = useCallback(
() =>
Expand Down Expand Up @@ -55,6 +56,8 @@ const CommonDetailsRows = ({
return [
volatilityType ? [{ value: 'Vol type' }, { value: volatilityType }] : null,
productType ? [{ value: 'Product' }, { value: productType }] : null,
expiryType ? [{ value: 'Expiry' }, { value: expiryType }] : null,

[
{ value: 'Exit Strategy' },
{ value: EXIT_STRATEGIES_DETAILS[exitStrategy].label }
Expand Down
3 changes: 3 additions & 0 deletions components/trades/atmStraddle/TradeSetupForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import ProductTypeComponent from '../../lib/ProductTypeComponent'
import VolatilityTypeComponent from '../../lib/VolatilityTypeComponent'
import RollbackComponent from '../../lib/RollbackComponent'
import SlManagerComponent from '../../lib/SlManagerComponent'
import ExpiryTypeComponent from '../../lib/ExpiryTypeComponent'

interface ATMStraddleTradeSetupFormProps {
formHeading?: string
Expand Down Expand Up @@ -113,6 +114,8 @@ const TradeSetupForm = ({

<ProductTypeComponent state={state} onChange={onChange} />

<ExpiryTypeComponent state={state} onChange={onChange} />

<Grid item xs={12}>
<TextField
fullWidth
Expand Down
3 changes: 3 additions & 0 deletions components/trades/atmStrangle/TradeSetupForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import ProductTypeComponent from '../../lib/ProductTypeComponent'
import RollbackComponent from '../../lib/RollbackComponent'
import DiscreteSlider from '../../lib/Slider'
import SlManagerComponent from '../../lib/SlManagerComponent'
import ExpiryTypeComponent from '../../lib/ExpiryTypeComponent'

interface ATMStrangleTradeSetupFormProps {
formHeading?: string
Expand Down Expand Up @@ -116,6 +117,8 @@ const TradeSetupForm = ({

<ProductTypeComponent state={state} onChange={onChange} />

<ExpiryTypeComponent state={state} onChange={onChange} />

<Grid item xs={12}>
<FormControl component='fieldset'>
<FormLabel component='legend'>Entry strategy</FormLabel>
Expand Down
3 changes: 3 additions & 0 deletions components/trades/directionalOptionSelling/TradeSetupForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import HedgeComponent from '../../lib/HedgeComponent'
import RollbackComponent from '../../lib/RollbackComponent'
import ProductTypeComponent from '../../lib/ProductTypeComponent'
import SlManagerComponent from '../../lib/SlManagerComponent'
import ExpiryTypeComponent from '../../lib/ExpiryTypeComponent'

interface DOSTradeSetupFormProps {
state: Partial<DIRECTIONAL_OPTION_SELLING_CONFIG>
Expand Down Expand Up @@ -114,6 +115,8 @@ const TradeSetupForm = ({

<ProductTypeComponent state={state} onChange={onChange} />

<ExpiryTypeComponent state={state} onChange={onChange} />

<Grid item xs={12}>
<TextField
fullWidth
Expand Down
12 changes: 9 additions & 3 deletions lib/browserUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ export const formatFormDataForApi = ({
martingaleIncrementSize,
strikeByPrice,
slmPercent,
exitStrategy
exitStrategy,
expiryType
} = data as DIRECTIONAL_OPTION_SELLING_CONFIG

const apiProps: DIRECTIONAL_OPTION_SELLING_TRADE = {
Expand All @@ -142,6 +143,7 @@ export const formatFormDataForApi = ({
martingaleIncrementSize: Number(martingaleIncrementSize),
slmPercent: Number(slmPercent),
maxTrades: Number(maxTrades),
expiryType,
strikeByPrice: strikeByPrice ? Number(strikeByPrice) : undefined,
...getSchedulingApiProps({
isAutoSquareOffEnabled,
Expand Down Expand Up @@ -169,7 +171,8 @@ export const formatFormDataForApi = ({
trailEveryPercentageChangeValue,
trailingSlPercent,
exitStrategy,
combinedExitStrategy
combinedExitStrategy,
expiryType
} = data as ATM_STRADDLE_CONFIG

const apiProps: ATM_STRADDLE_TRADE = {
Expand All @@ -184,6 +187,7 @@ export const formatFormDataForApi = ({
exitStrategy,
combinedExitStrategy
}),
expiryType,
maxSkewPercent: Number(maxSkewPercent),
thresholdSkewPercent: Number(thresholdSkewPercent),
...getSchedulingApiProps({
Expand Down Expand Up @@ -212,7 +216,8 @@ export const formatFormDataForApi = ({
trailingSlPercent,
exitStrategy,
expireIfUnsuccessfulInMins,
combinedExitStrategy
combinedExitStrategy,
expiryType
} = data as ATM_STRANGLE_CONFIG

const apiProps: ATM_STRANGLE_TRADE = {
Expand All @@ -227,6 +232,7 @@ export const formatFormDataForApi = ({
exitStrategy,
combinedExitStrategy
}),
expiryType,
inverted: Boolean(inverted),
...getSchedulingApiProps({
isAutoSquareOffEnabled,
Expand Down
30 changes: 30 additions & 0 deletions lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ export interface INSTRUMENT_PROPERTIES {
freezeQty: number
}

export interface KITE_INSTRUMENT_INFO {
exchange: string // "NFO"
exchange_token: string // "36320"
expiry: string // "2021-10-28"
instrument_token: string // "9297922"
instrument_type: string // "CE"
last_price: string // "0"
lot_size: string // "50"
name: string // "NIFTY"
segment: string // "NFO-OPT"
strike: string // "17350"
tick_size: string // "0.05"
tradingsymbol: string // "NIFTY21OCT17350CE"
}

export const INSTRUMENT_DETAILS: Record<INSTRUMENTS, INSTRUMENT_PROPERTIES> = {
[INSTRUMENTS.NIFTY]: {
lotSize: 50,
Expand Down Expand Up @@ -86,6 +101,18 @@ export enum VOLATILITY_TYPE {
SHORT = 'SHORT'
}

export enum EXPIRY_TYPE {
CURRENT = 'CURRENT',
NEXT = 'NEXT',
MONTHLY = 'MONTHLY'
}

export const EXPIRY_TYPE_HUMAN = {
[EXPIRY_TYPE.CURRENT]: 'Current weekly',
[EXPIRY_TYPE.NEXT]: 'Next weekly',
[EXPIRY_TYPE.MONTHLY]: 'Current Monthly'
}

export enum STRANGLE_ENTRY_STRATEGIES {
DISTANCE_FROM_ATM = 'DISTANCE_FROM_ATM',
DELTA_STIKES = 'DELTA_STIKES'
Expand Down Expand Up @@ -136,6 +163,7 @@ export const STRATEGIES_DETAILS = {
trailingSlPercent: NEXT_PUBLIC_DEFAULT_SLM_PERCENT,
productType: PRODUCT_TYPE.MIS,
volatilityType: VOLATILITY_TYPE.SHORT,
expiryType: EXPIRY_TYPE.CURRENT,
runNow: false,
expireIfUnsuccessfulInMins: 10,
exitStrategy: EXIT_STRATEGIES.INDIVIDUAL_LEG_SLM_1X,
Expand Down Expand Up @@ -173,6 +201,7 @@ export const STRATEGIES_DETAILS = {
deltaStrikes: 20,
productType: PRODUCT_TYPE.MIS,
volatilityType: VOLATILITY_TYPE.SHORT,
expiryType: EXPIRY_TYPE.CURRENT,
runNow: false,
exitStrategy: EXIT_STRATEGIES.INDIVIDUAL_LEG_SLM_1X,
slOrderType: SL_ORDER_TYPE.SLL,
Expand Down Expand Up @@ -214,6 +243,7 @@ export const STRATEGIES_DETAILS = {
martingaleIncrementSize: 1,
isHedgeEnabled: true,
productType: PRODUCT_TYPE.MIS,
expiryType: EXPIRY_TYPE.CURRENT,
hedgeDistance: 2000,
entryStrategy: DOS_ENTRY_STRATEGIES.FIXED_TIME,
exitStrategy: EXIT_STRATEGIES.MIN_XPERCENT_OR_SUPERTREND,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const optionSellerEntryWatcher = async ({
addHedge
}) => {
try {
const { user, orderTag, instrument } = initialJobData
const { user, orderTag, instrument, expiryType } = initialJobData
const kite = syncGetKiteInstance(user)
const orderHistory = await kite.getOrderHistory(limitOrderAckId)
const revOrderHistory = orderHistory.reverse()
Expand Down Expand Up @@ -81,7 +81,8 @@ const optionSellerEntryWatcher = async ({
completedOrder.tradingsymbol.length - 2,
completedOrder.tradingsymbol.length - 1
),
user
user,
expiry: expiryType
})

const hedgeOrder = {
Expand Down
1 change: 1 addition & 0 deletions lib/queue-processor/tradingQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ async function processJob (job: Job) {
data,
data: { strategy }
} = job
console.log(`[job processing] Beginning job processing for ${strategy}`)
switch (strategy) {
case STRATEGIES.ATM_STRADDLE: {
return atmStraddle(data)
Expand Down
59 changes: 58 additions & 1 deletion lib/session.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,70 @@
// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import { withIronSession } from 'next-iron-session'
import { KiteConnect } from 'kiteconnect'
// NB: not the best place to require these
// ideally these should live in their own file that gets included as a middleware
import './queue-processor'
import './exit-strategies'
import './watchers'
import { setUserSession, premiumAuthCheck } from './utils'
import { KiteProfile } from '../types/kite'

const withAdminCheck = handler => {
return async function withAdminWrapper (req, res) {
const sxApiKey = req.headers['signalx-api-key']
const kiteApiKey = req.headers['signalx-kite-key']
const kiteAccessToken = req.headers['signalx-kite-token']

if (!sxApiKey && !kiteApiKey) {
// UI based flow
return handler(req, res)
}

// for premium and club users
let validSxUser = false
try {
validSxUser = await premiumAuthCheck()
} catch (e) {
validSxUser = false
}

// block intrusion
if (!validSxUser) {
return handler(req, res)
}

if (!kiteAccessToken) {
// sx admin work, no broker authorization
await setUserSession(req, {} as KiteProfile)
} else {
console.log(
'key and token found in headers. attempting to connect kite and save session'
)
try {
const kc = new KiteConnect({
api_key: kiteApiKey,
access_token: kiteAccessToken
})

const kiteProfile = await kc.getProfile()
await setUserSession(req, {
access_token: kiteAccessToken,
...kiteProfile
})
console.log('session generated from headers')
return handler(req, res)
} catch (error) {
console.log(error)
return res
.status(403)
.send('Forbidden. Unauthorized key or token provided')
}
}
}
}

export default function withSession (handler) {
return withIronSession(handler, {
return withIronSession(withAdminCheck(handler), {
password: process.env.SECRET_COOKIE_PASSWORD!,
cookieName: 'khaching/kite/session',
cookieOptions: {
Expand Down
Loading