Search This Blog

Showing posts with label program. Show all posts
Showing posts with label program. Show all posts

Wednesday, October 13, 2021

Security : Java PHP encryption decryption for AES-128-CTR or AES/CTR/NoPadding

 Java

package com.security;

import java.util.Base64;


import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;


/**

 * @author drvijay

 * @date 13-0ct-2021

 */


public class EncryptDecrypt

{

private static String encrypt ( String data, String cipherType, String key, String iv )

{

String encrypted = "";


try

{

Cipher encryptionCipher = Cipher.getInstance ( cipherType );

IvParameterSpec ivv = new IvParameterSpec ( iv.getBytes ( "UTF-8" ), 0, encryptionCipher.getBlockSize () );

encryptionCipher.init ( Cipher.ENCRYPT_MODE, new SecretKeySpec ( key.getBytes (), "AES" ), ivv );

// encrypt

byte [] cipherText = encryptionCipher.doFinal ( data.getBytes () );


encrypted = new String ( Base64.getEncoder ().encode ( cipherText ) );

}

catch ( Exception e )

{

throw new IllegalStateException ( e );

}

return encrypted;

}


private static String decrypt ( String encryptData, String cipherType, String key, String iv )

{

String decrypted = "";

try

{


Cipher decryptionCipher = Cipher.getInstance ( cipherType );

IvParameterSpec ivv = new IvParameterSpec ( iv.getBytes ( "UTF-8" ), 0, decryptionCipher.getBlockSize () );


SecretKeySpec secretKeySpec = new SecretKeySpec ( key.getBytes (), "AES" );

decryptionCipher.init ( Cipher.DECRYPT_MODE, secretKeySpec, ivv );

// decrypt

byte [] finalCipherText = decryptionCipher.doFinal ( Base64.getDecoder ().decode ( encryptData ) );

// converting to string

String finalDecryptedValue = new String ( finalCipherText );

decrypted = finalDecryptedValue;

}

catch ( Exception e )

{

throw new IllegalStateException ( e );

}

return decrypted;

}


public static void main ( String [] args )

{

String cipherType = "AES/CTR/NoPadding";

String valueToEncrypt = "hello, vijay";

String key = "0123456789abcdef";

String iv = "2208250639374785";


String encrypted = encrypt ( valueToEncrypt, cipherType, key, iv );

String decrypted = decrypt ( encrypted, cipherType, key, iv );


//System.out.println(Base64.getDecoder ().decode ( "ycbnIE8vn2lTUi/9F/FEa+5v86qzOU09yjdxfGDc8wA=" ));

// END OF ENCODE CODE

System.out.println ( "encrypted and saved as Base64 : " + encrypted );


System.out.println ( "decrypted from Base64->aes128 : " + decrypted );

// END OF DECRYPT CODE


}

}




PHP code

<!DOCTYPE html>

<html>

<body>

<?php

$simple_string = "hello, vijay";

echo ($simple_string .'<br/>');

        $ciphering = 'AES-128-CTR';

        $iv_length = openssl_cipher_iv_length($ciphering);

        $options = 0;

        // Non-NULL Initialization Vector for encryption

        $iv = '2208250639374785';


       

        $key = '0123456789abcdef';


                $encryption = openssl_encrypt($simple_string, $ciphering,

                    $key, $options, $iv); 

                    echo($encryption .'<br/>');

                    

                  $decryption=openssl_decrypt ($encryption, $ciphering,

                $key, $options, $iv);

                echo($decryption .'<br/>');

                

?>


</body>

</html>



output

hello, vijay
0iQoUVC/QZG3cM20
hello, vijay

Monday, October 11, 2021

Java to Do ImageMagick Call

 package com.product.zilly;


import java.io.File;

import java.util.Map;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


/**

 * @author drvijay

 * @description img class

 * @version 1.0

 */


@SuppressWarnings ("all")

public class TestModules implements Constants

{

private static final Logger logger = LoggerFactory.getLogger ( TestModules.class );


public static void main ( String args[] )

{

ImageHelper imageHelper = new ImageHelper ();

String renditionPath = "/home/drvijay/images"; 

String rendtionPathCategory = "/home/drvijay/images"; 

String startingMainPath = renditionPath + PATH_SEPARATOR + SkuRendition.main;

String startingCategoryMainPath = rendtionPathCategory + PATH_SEPARATOR + SkuRendition.main; // for category images main path

imageHelper.loadSkuImageProperties ();

boolean imageOverride = false; 

File rotated = null;

File file = new File ( startingMainPath + PATH_SEPARATOR + "sample.png" );

if ( file.isFile () && file.exists () )

{

Map <SkuRendition, Map <Resolution, DimInfo>> dimensions = imageHelper.getAllDimensions ();

logger.debug ( dimensions.toString () );

for ( SkuRendition skuRendition : dimensions.keySet () )

{

try

{

Map <Resolution, DimInfo> resolutions = dimensions.get ( skuRendition );

for ( Resolution resolution : resolutions.keySet () )

{

DimInfo dimInfo = resolutions.get ( resolution );


File isExist = new File ( renditionPath + PATH_SEPARATOR + skuRendition.name () + PATH_SEPARATOR + resolution.name () + UNDER_SCORE + file.getName () );

if ( ( imageOverride && isExist.isFile () && isExist.exists () ) || ( !isExist.isFile () && !isExist.exists () ) )

{

rotated = imageHelper.processImage ( file, imageHelper.getOutputDir ( renditionPath, skuRendition.name () ), dimInfo, resolution.name () );

logger.debug ( "Generated : " + rotated.getAbsolutePath () );

}


}

}

catch ( Exception e )

{

logger.error ( "Error : " + e );

}

finally

{


/*

* if ( rotated != null )

* {

* rotated.delete ();

* }

*/


}

}

}

}

}


//Iamge Process

public File processImage ( File inFile, File outputDir, DimInfo dimInfo, String resolution ) throws Exception

{

String fileName = resolution + UNDER_SCORE + inFile.getName ();

// String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

// String fileNameExt = FilenameUtils.getExtension ( fileName );


// check for windows and set the image magick home manually to avoid error.

String OS = System.getProperty ( "os.name" ).toLowerCase ();

if ( ( OS.indexOf ( "win" ) >= 0 ) )

{

// linux - "/usr/lib/mime/packages/imagemagick-6.q16";

String myPath = "C:/Program Files/ImageMagick-6.9.2-Q16"; // globalMaster.getSystemProperties ().get ( KEY_PATH_HOME_IMAGE_MAGICK ).getValue ();

ProcessStarter.setGlobalSearchPath ( myPath );

}

ConvertCmd convert = new ConvertCmd ();

IMOperation operation = new IMOperation ();

String input = inFile.getAbsolutePath ();

int tmbWidth = dimInfo.getWidth ();

int tmbHeight = dimInfo.getHeight ();


operation.addImage ( input );

operation.gravity ( LocalProperties.getPropertyValue ( "render.image.gravity" ) );

operation.thumbnail ( tmbHeight, tmbWidth );

operation.units ( LocalProperties.getPropertyValue ( "render.image.units" ) );

operation.density ( Integer.parseInt ( LocalProperties.getPropertyValue ( "render.image.density" ) ) );

operation.strip ();

operation.interlace ( LocalProperties.getPropertyValue ( "render.image.interlace" ) );

operation.gaussianBlur ( Double.parseDouble ( LocalProperties.getPropertyValue ( "render.image.gaussian.blur" ) ) );

operation.quality ( Double.parseDouble ( LocalProperties.getPropertyValue ( "render.image.quality" ) ) );


File retVal = new File ( outputDir, fileName );

operation.addImage ( retVal.getAbsolutePath () );

convert.run ( operation );


logger.debug ( "Preview file: " + retVal.getAbsolutePath () );

return retVal;

}


Wednesday, June 30, 2021

Python - Image to Pdf

1. Install img2pdf

> pip/pip3 install img2pdf

2. img2pdfown.py


# importing necessary libraries

import img2pdf

from PIL import Image

import os

  

# CLI  img2pdf *jpg -o output_all_pngs.pdf

'''

img_path = "image1.jpg";

pdf_path = "output.pdf";

image = Image.open(img_path);

pdf_bytes = img2pdf.convert(image.filename);

file = open(pdf_path, "wb");

file.write(pdf_bytes);

image.close();

file.close();

'''


# convert all files ending in .jpg inside a directory

dirname = "dump/images/"

imgs = []

#dpix = dpiy = 300;

#layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

for fname in os.listdir(dirname):

    if not fname.endswith(".jpg"):

        continue

    path = os.path.join(dirname, fname)

    if os.path.isdir(path):

        continue

    imgs.append(path)

    print ("\n" + path);

with open("dump/output.pdf", "wb") as f:

    #f.write(img2pdf.convert(imgs, layout_fun=layout_fun));

    f.write(img2pdf.convert(imgs));

  

'''    

imgs = ['dump/images/page_1.jpg', 'dump/images/page_2.jpg', 'dump/images/page_10.jpg']

with open("dump/output1.pdf", "wb") as f:

    f.write(img2pdf.convert(imgs))


# specify paper size (A4)

a4inpt = (img2pdf.mm_to_pt(210), img2pdf.mm_to_pt(297))

layout_fun = img2pdf.get_layout_fun(a4inpt)

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# use a fixed dpi of 300 instead of reading it from the image

dpix = dpiy = 300;

layout_fun = img2pdf.get_fixed_dpi_layout_fun((dpix, dpiy))

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', layout_fun=layout_fun))


# create a PDF/A-1b compliant document by passing an ICC profile

with open("name.pdf", "wb") as f:

    f.write(img2pdf.convert('test.jpg', pdfa="/usr/share/color/icc/sRGB.icc"))    

'''

    


Friday, June 18, 2021

React Native - Check Application is in Background or ForeGround with Time Diff - 10 seconds Move to Login Session Expired

 1. Install the below two mandatory npm plugins.

npm install --save react-native-async-storage

npm install --save moment


2. app.js


import React, { Component } from 'react';
import { StyleSheet, Text, View, AppState } from 'react-native';
//import Routing from "./src/routing/routing";
import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';
//import { Actions } from 'react-native-router-flux';

export default class App extends Component {
constructor() {
super();
this.state = {
appState: AppState.currentState
}
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = async(nextAppState) => {
this.setState({ appState: nextAppState });
if (nextAppState === 'background') {
var previousTime = new Date();
await AsyncStorage.setItem( "previousTime", previousTime.toString() );
// Do something here on app background.
console.log( "App is in Background Mode @ ", previousTime );
}
if (nextAppState === 'active') {
// Do something here on app active foreground mode.
const start = moment( await AsyncStorage.getItem('previousTime') );
const end = moment();
//in original implementation, use minutes and check with N value.
//const range = end.diff(start,'minutes');
const range = end.diff(start,'seconds');
if ( range >= 10 ){
console.log ( "App is exit the Active Range, So moving to Login screen." );
/* Actions.login({"message":"Session Exit"} ); */
}
else{
console.log( "App is in Active Range, So continue your process ...");
}
}
if (nextAppState === 'inactive') {
// Do something here on app inactive mode.
console.log("App is in inactive Mode.")
}
};
render() {
return (
<View style={styles.MainContainer}>
{/* <Routing /> */}
<Text>Current state is: {this.state.appState}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
color: '#000'
}
});

Monday, October 5, 2020

Ubuntu - Maven - SSL Error while doing mvn clean install

sudo dpkg --purge --force-depends ca-certificates-java sudo apt-get install ca-certificates-java sudo update-ca-certificates -f

Tuesday, June 30, 2020

Spring Boot Hibernate 5 com.zaxxer.hikari.pool. active Connection is not Release

1. maxpoolsize = 100
2. idle time out = reduced to 10 seconds
3. save method in repo/services classes should close in entityManager
close in finally block {}
4. also told spring to use hibernate5.SpringContext in application.properties

 
4th application.properties

spring.datasource.hikari.leak-detection-threshold=10000
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

1 & 2 in HikariPool Datasource settings

url=xxx
username=xx
password=xx
driverClassName=com.mysql.jdbc.Driver
connectionTimeout=30000
maxPoolSize=100
idleTimeout=10000
minIdle=10
poolName=xxxdb-connection-pool


3rd - EntityManager Connection close
 EntityManager entityManager = entityManagerFactory.createEntityManager ();
        try
        {
            if ( entityManager != null )
            {
                entityManager.getTransaction ().begin ();
                entityManager.merge ( xxx );
                entityManager.getTransaction ().commit ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( e.getMessage () );
        }
        finally
        {
            if ( entityManager != null )
            {
                entityManager.close ();
            }
        }






Tuesday, May 19, 2020

Linux Ubuntu - OpenJdk Java 13 Install Setup

To uninstall OpenJDK
> sudo apt-get autoremove openjdk*
> sudo apt-get purge openjdk*
  
Install > 1.9 JDK 1.3

> sudo apt install -y curl

> curl -O https://download.java.net/java/GA/jdk13/5b8a42f3905b406298b72d750b6919f6/33/GPL/openjdk-13_linux-x64_bin.tar.gz

> tar xvf openjdk-13_linux-x64_bin.tar.gz

> sudo mv jdk-13 /usr/java/

> sudo nano /etc/profile
     # Go to after fi end and paste the below lines
    JAVA_HOME=/usr/java/jdk-13.0.2
    PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
    export JAVA_HOME
    export JRE_HOME
    export PATH


# Configure Java Alternatives
> sudo update-alternatives --install "/usr/bin/java" "java" "/usr/java/jdk-13.0.2/bin/java" 1

# Configure Javac Alternatives
> sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/java/jdk-13.0.2/bin/javac" 1

# Check version
> java -version

# Use only in case of multiple JDKs installed

# Configure Java
> sudo update-alternatives --config java

# Configure Java Compiler
> sudo update-alternatives --config javac

>javac -version

>java version


Wednesday, February 26, 2020

Pytesseract Read a image and labeled or Rename as filename

pytesseract_image.py

import cv2
import os
import pytesseract
try:
    from PIL import Image
except ImportError:
    import Image

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

#for x in range (1,1000): 
#    img_cv = cv2.imread(r'D:/Temp/Captcha/program/'+ str(x) + '.png')

folderpath = "D:/Temp/Captcha/program/"
for filename in os.listdir(folderpath):   
    img_cv = cv2.imread(r'D:/Temp/Captcha/program/'+ filename )
    # By default OpenCV stores images in BGR format and since pytesseract assumes RGB format,
    # we need to convert from BGR to RGB format/mode:
    img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
    imagetext = pytesseract.image_to_string(img_rgb)
    print (imagetext)
    # OR
    #img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 0)
    #imagetext = pytesseract.image_to_string(img_rgb)
    #print (imagetext)
    src =folderpath+ filename
    dst =folderpath+ imagetext + ".png"
    os.rename(src, dst)


NOTE:
save filenmae other than pytesseract.py - Note: to avoid pytesseract.image_to_string not found error

Python - Download Captcha Images

import requests
import os
from random import randint

for x in range(100, 1000):
    url = ""
    payload = {}
    headers= {}
    response = requests.request("GET", url, headers=headers, data = payload)
    #print(response.text.encode('utf8'))
   
    url = ""
    payload = {}
    response = requests.request("GET", url, cookies=response.cookies)
   
    f_ext = x
    f_name = 'D:/Temp/Captcha/{}.png'.format(f_ext)
    with open(f_name, 'wb') as f:
        f.write(response.content)
   
    print("Iteration : " + str(x) )

print( "Done !")

Friday, August 30, 2019

Python Code to pull NSE Option Derivative HTML to JSON on Every N minutes

1. Install Python, PIP
2. type the below command from your python sample folder [ by pip or pip3 cmd ].
     pip install beautifulsoup
     OR
     pip install BeautifulSoup4
     pip install requests
     pip install schedule
     python nse_options.py

-- ENJOY

nse_options.py

# author - dr. vijay
# email - drvijayy2k2@gmail.com
# date - 30-08-2019 7:30 PM

# install plugin
# pip install BeautifulSoup

import sys
import json
import requests
# Schedule Library imported
import schedule
import time
import datetime

from bs4 import BeautifulSoup

base_url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbol=';


def doScheduler ():
    print ( "Schedule starts @ ", datetime.datetime.now() );
    result = parseNseOptions ( 'NIFTY' );
    # result = parseNseOptions ( 'INFY' );
    f = open( 'D:/nseOptionst.txt', 'a' )
    f.write( str(result) + "\n" );
    print ( "Done !" );
 

def parseNseOptions ( scrip='NIFTY' ):
    url = base_url + scrip;
    response = response = requests.get( url ) 
    if( response != None and response.ok ):
        optionScripListHtml = response.content
        # print ( optionScripListHtml );
        soup = BeautifulSoup( optionScripListHtml, "html.parser" )
        tableHtml = soup.find( "table", id="octable" )
        f1 = tableHtml.findAll( "thead" )[0].findAll( 'tr' )
     
        callDataColumnEndsAt = 11
        optionStrikePriceColumnAt = ( 12 - 1 )
        putDataColumnEndsAt = 23
        headers = {}
        headersOnIndex = {}
        h1 = f1[1].findAll( "th" )
        for index, h in enumerate( h1, start=0 ):
            if ( index < callDataColumnEndsAt ):
                headers["call-" + h.text] = h.get( "title", "" )
                headersOnIndex[index] = "call-" + h.text 
            elif ( index == optionStrikePriceColumnAt ):
                 headers[h.text] = h.get( "title", "" )
                 headersOnIndex[index] = h.text 
            elif ( index < putDataColumnEndsAt ):
                headers["put-" + h.text] = h.get( "title", "" )
                headersOnIndex[index] = "put-" + h.text 
        # print(headersOnIndex)
     
        fnoDataRows = tableHtml.findAll( "tr" )
        tempMap = {}
        totalOptionPCOI = {}
        tempMapWithStrikePriceAsKey = {}
        startingRow = 3
        endingRow = len( fnoDataRows )
        callOIChangeCol = 2
        callTotalChangeInOIValue = 0
        putOIChangeCol = 20
        putTotalChangeInOIValue = 0
        index = 1
        colIndex = 1
        recordFound = False
     
        for rowIndex, x in enumerate( fnoDataRows, start=0 ):
            if ( rowIndex == endingRow - 1 ):
                xx = x.findAll( "td" )
                totalOptionPCOI = {"callTotalOI": xx[1].text, "callTotalChangeInOI": xx[2].text, "callTotalVolume": xx[3].text, "putTotalVolume": xx[5].text, "putTotalChangeInOI": xx[6].text, "putTotalOI": xx[7].text }
                # break the entire loop as we got all the information
                break;
            for colIndex, c in enumerate( x.findAll( "td" ), start=0 ):
                value = c.text.strip()
                if value == "" or value == "-":
                    value = "0"
                else:
                    value = value.replace( ",", "" )
             
                if ( colIndex == callOIChangeCol ):
                    callTotalChangeInOIValue = callTotalChangeInOIValue + int( value )
                if ( colIndex == putOIChangeCol ):
                    putTotalChangeInOIValue = putTotalChangeInOIValue + int( value )
                     
                tempMap[ headersOnIndex[colIndex]] = value
                recordFound = True
             
            if recordFound == True:
                tempMapWithStrikePriceAsKey[tempMap[headersOnIndex[optionStrikePriceColumnAt]]] = tempMap.copy()
                strikePrice = tempMap["Strike Price"]
                tempMap.clear()   

            recordFound = False
     
        return dict( { "resultFetchTime": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "totalOptionPCOI":totalOptionPCOI, "mapWithStrikePriceAsKey":tempMapWithStrikePriceAsKey} )


if __name__ == "__main__":
 
    schedule.every( 3 ).minutes.do( doScheduler )
    while True:
        schedule.run_pending()
        time.sleep( 1 )


OUTPUT

{
'mapWithStrikePriceAsKey': {
//..... other strike prices
'10850.00': {
'call-Chart': '0',
'call-OI': '49950',
'call-Chng in OI': '26475',
'call-Volume': '10689',
'call-IV': '14.71',
'call-LTP': '210.75',
'call-Net Chng': '29.00',
'call-BidQty': '300',
'call-BidPrice': '208.85',
'call-AskPrice': '215.95',
'call-AskQty': '75',
'Strike Price': '10850.00',
'put-BidQty': '300',
'put-BidPrice': '19.50',
'put-AskPrice': '20.45',
'put-AskQty': '600',
'put-Net Chng': '-25.55',
'put-LTP': '20.45',
'put-IV': '14.92',
'put-Volume': '134223',
'put-Chng in OI': '261600',
'put-OI': '399750',
'put-Chart': '0'
},
'10900.00': {
'call-Chart': '0',
'call-OI': '574650',
'call-Chng in OI': '198600',
'call-Volume': '157457',
'call-IV': '14.15',
'call-LTP': '169.05',
'call-Net Chng': '26.85',
'call-BidQty': '4350',
'call-BidPrice': '169.05',
'call-AskPrice': '170.85',
'call-AskQty': '75',
'Strike Price': '10900.00',
'put-BidQty': '150',
'put-BidPrice': '27.45',
'put-AskPrice': '28.20',
'put-AskQty': '525',
'put-Net Chng': '-33.60',
'put-LTP': '28.20',
'put-IV': '14.22',
'put-Volume': '396350',
'put-Chng in OI': '894450',
'put-OI': '1796100',
'put-Chart': '0'
}
  //..... other strike prices
},
'totalOptionPCOI': {
'callTotalOI': ' 12,057,225',
'callTotalChangeInOI': '',
'callTotalVolume': ' 2,231,841',
'putTotalVolume': ' 1,883,484',
'putTotalChangeInOI': '',
'putTotalOI': ' 12,479,775'
}

}

Tuesday, August 27, 2019

Telegram - Broadcast or Send Message through Programming Java Python C# VB

1. Create a bot token through @botfather.
           1.1 Install Telegram
           1.2 Login to telegram
           1.3 on Search window type @botfather and select
           1.4 type one by one until you see Done !, Congratulations , your token
                     /start
                     /newbot
                    drvautobot     (username)
                   
                   Done !, ...
                   token    123456:dsfd..

2. Copy this token and keep it.
   
3. Open telegram and create new channel.
     Ex: autobot
     3.1 open autobot channel window
     3.2 click on top to see administrators , click
     3.3 search @drvautobot (bot username), select
     3.4 assign as administrator

Thats it.
Now use browser or programing with GET method.

browser
https://api.telegram.org/bot/sendMessage?chat_id=@&text=hello

ex: https://api.telegram.org/bot123456:dsfdadsfsdfdsfahgjhgsfd/sendMessage?chat_id=@autobot&text=hello

response 
{"ok":true,"result":{"message_id":2,"chat":{"id":-1001493064021,"title":"Autobot","username":"infovijay","type":"channel"},"date":1566909775,"text":"hello"}}




open your channel window and see the text hello.


Enjoy

Friday, August 2, 2019

Post Market Nifty View - 04-06-2019

#. Today FII are net buyers involves major money. and nifty totally surge to 12050k + mark.

#. Day Candle - Nifty forms strong bullish candle. But it has near to the major resistance of 12146, once it break and closed. then we have a strong upwards and next major hurdle at 12411 +.

#. wednesday is holiday and thursday monetary policy, hope repo rate will cut by 0.25% and that creates BN volatility ..

#. Short 32100 CE and planning to hedge by tomorrow evening if it close above 31800.

#. Short nifty PE heavily and hedge nifty future and short CE with less qty. I need this expiry to end below 12150 and I can get decent money.


Happy Trading..

Thursday, July 18, 2019

Java RabbitMQ - Sample Send Receiver

//path lib setting
set CLASSPATH=.;lib\amqp-client-5.4.1.jar;lib\*.jar;lib\slf4j-api-1.7.26.jar;

//compile
javac TestSender.java

//run
java TestSender


TestSender.java

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class TestSender
{

private final static String QUEUE_NAME = "rmq";

public static void main ( String [] argv ) throws Exception
{
ConnectionFactory factory = new ConnectionFactory ();
factory.setHost ( "192.168.7.11" );
factory.setPort ( 8890 ); //always give HA port to test if you want to do HA testing. else give queue port
factory.setUsername ( "test" );
factory.setPassword ( "test" );
try (Connection connection = factory.newConnection ();
Channel channel = connection.createChannel ())
{
channel.queueDeclare (QUEUE_NAME, true, false, false, null );
String message = "Hello World111!";
channel.basicPublish ( "", QUEUE_NAME, null, message.getBytes ( "UTF-8" ) );
System.out.println ( " [x] Sent '" + message + "'" );
}
}
}


TestReceiver.java

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class TestReceiver
{

private final static String QUEUE_NAME = "rmq";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost ( "192.168.7.13" );
factory.setPort ( 5672 ); //always receive with your default queue port and not HA port
factory.setUsername ( "test" );
factory.setPassword ( "test" );

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
}



NOTE: channel.queueDeclare (QUEUE_NAME, true, false, false, null ); //if durable else give false instead of true.

Tuesday, July 2, 2019

Python - Expecting property key name enclosed in double quotes - String to JSON

import demjson 
result = demjson.decode(' { key: "value" }' )


demjson plugin is very good on this

- Enjoy 

Thursday, June 13, 2019

Subversion - SVN Clean UP - previous operation has not finished

  • Right click on folder
  • Go to TortoiseSVN -> Clean Up...
  • Make sure the option to Break Locks is ticked and click OK

- Enjoy

Wednesday, June 5, 2019

Pre Open Market Walk Through - Weekly Expiry - 05-06-2019

Important -  Monetary Policy announcement, So watch Bank nifty stocks, that impact will be more in Nifty direction.


1. Expiry - Weekly

2. Global Market:
            US            - Flat
            European  - Green
            Asian        - Mixed
           SGX Nifty - Down with 51 pts

3. FII/DII activities 
                 FII are net sellers of 416cr and DII are also net sellers of 355cr.   
                 Generally FII will buy or sell continuesly.

4. Candles - Nifty forms harami or inside bar candle pattern in days candle..
                     So buy above yest high and sell below yest low and day before high/low is Ur stop-loss. Trade the next week option strikes if you go on long to escape from Theta.

                     BANK NIFTY - Tomorrow monetary policy announce at 2:30 or 4PM.  So be caution and play on hedging.. Your hedging premimum price should not [both CE and PE] goes beyond 100 RS combine and also Straddle only. 

5. VIX is at 15.63 is good for bull market. 

6. USD/INR $ - 69.42 but still it has to come below 69 is good for investment or bull market.

7. Result/Events - Monetary policy, expect the rate cut of basis 25 pts, so second half may expect some volatility. But this news already spread and the market is played well already.

   NOTE - Any more rate cut rather than 25 basis pts will take market to upwards of another 100-200 pts in BN.

8. Max Pain   -  Nifty @ 11800, BN @ 31600.

9. FNO Analasis -   Features              - Nifty - Bullish & BN - Neutral
                                 Option PC Ratio - Nifty - Neutral & BN - Neutral

10. Trend Movements - Nifty may end between 11930-12075.





My Trade Plan
#############

#. Already Short Strangle at OTM 11800, 11850,11900 PE and 12150, 12200 CE, BN done hedging [bullish combo spread].

             Nifty [  Close existing positions which ever below 0.5 and shift to next position with minimal until the direction gets cleared. second half may go with ATM short stradle if required].

Already I made VEGA netural, If that strategy fails, then i will play ITM stradle to make delta neutral.


#. LOTS - Confidential*





TRADE WITH CAUTION
HAPPY TRADING
Vijay




- Please feel free to comment and always respected, it will be answered latter.-

Monday, June 3, 2019

Post Market Nifty View - 03-06-2019

#. Vix - 15.97 (-0.62%) decreased- which is good

#. US $ - 69.42  (-0.69%) decreased - so can expect some FII investment

#. Today FII are net buyers involves major money. and nifty totally surge to 12050k + mark.

#. Day Candle - Nifty forms strong bullish candle. But it has near to the major resistance of 12146, once it break and closed. then we have a strong upwards and next major hurdle at 12411 +.

#. wednesday is holiday and thursday monetary policy, hope repo rate will cut by 0.25% and that creates BN volatility ..

#. Short 32100 CE and planning to hedge by tomorrow evening if it close above 31800.

#. Short nifty PE heavily and hedge nifty future and short CE with less qty. I need this expiry to end below 12150 and I can get decent money.


Happy Trading..

Wednesday, May 29, 2019

Post Market Nifty View - 29-05-2019

#. Vix - 16.41 (3.08%) increased
#. US $ - 69.84  (0.23%) increased
#. Day Candle - Nifty forms bearish spining top after yesterday hanging man pattern, so tomorrow we can see further downside if nifty break todays low. 
#. June serious might be bullish once FII, FDI comes inside.



#. Tomorrow is weekly & monthly expiry, so be caution.

Tuesday, May 28, 2019

Post Market Nifty View - 28-05-2019



Nifty forms hanging man pattern in day/monthly candle and also it is on the highest level. so there may be a slight pull down in coming sessions. but june serious will drive by modi, budget, monitary policy in upwards..

Wednesday, May 15, 2019

Post Market Analysis :: NSE Nifty Report - 15-05-2019


#. Vix - 28.66 (5.64%) increased  and it will cause major impact in the market,

#. US $ - 70.43 (0.22%) decreased, Still it has to decrease and come below 69 INR, so we can expect more FII investment.

#. Day Candle -  Nifty forms long red candle in day candle,
   Next major support at 11025 and BN at 28120 if the same volatility continues.

Nifty

#. Hdfcbank split options is on may 22 nd.

#. Upto election result, we will expect the volatility in the market.

#. Tomorrow is weekly expiry, so be caution.




- Vijay

Hit Counter


View My Stats