Black Scholes says C= SN(d1) - Xexp(-rt)N(d2) = exp(-rt){SN(d1)exp(rt)-XN(d2)},
So for risk-neutral, N(d2)= Pr(Price end up above Strike).
Digital Call = Pay M if expired above X. So Digital Call Value =exp(-rt)MN(d2).
In general with Yield,
C=exp(Y-r)tMN(d2)
P=exp(Y-r)tMN(-d2)
Sunday, April 5, 2009
Digital Call Option value = exp(-rt)N(d2)
Forward Start Call Option = Straight Call Option
This only be true when all of the following are true:
(1) Forward Start is designed to be at-money-call.
(2) Interest Rate and Volatility are constant.
Using Black-Scholes Model, give Forward Start time periods [t1,T1] and calls
are at the money at t=0 and t=t1, we would have call value c, c1 both are proportional to stock price S, S1. Therefore c1= c(S1/S).
Under risk-nerual, S1= Random variable but E[S1]*exp(-rt1]=S or E[S1]=exp(rt1]S
==> value of forward start call at t=0 = exp(-rt1)E[c1]=exp(-rt1)cE[S1]/S=c
That is V-ForwardStart Call(t=0) = C expiring in T1-t1 days.
To really make interest rate and Volality constant, we will need to enter IR swap and Volatility Swap (Pay floating, receiv fixed)
Friday, March 13, 2009
How to read Crash Dump file (.mdmp) using VS.net 2008
(1) Locate Dump file under doucments and settings\user\localsetting\Application Data\PC health\
(2) open .mdump using VS 2008 and run to break exception.
(3) load SOS.dll by ".load sos" command in the immediate windows.
(4) All the sos command now avaible !help list all command
(5) eg. !pe --- Print Exception and stack trace, !DumpStack, !CLRStack, !EEStack
Also you may need to load symbol from Microsoft Symbol Server, Tool->Options-> Debugging->Symbols --> uncheck "Search ...Manually"
Monday, March 2, 2009
DPAPI Encrypted Password in Database
XIP SDK need password to login. So to use DPAPI encryption we need the scheme with the following properties:
(1) Have to allow encryption per machine
(2) easy to change password once in database to trigger change accross all machines
PASSWORD Schema
CREATE TABLE [dbo].JQD_PASSWORD(
[USER_ID] [varchar](50) NOT NULL,
[PASSWORD] [varchar](1000) NOT NULL,
[NEW_PASSWORD] [varchar](500) NOT NULL,
[INSTALL_MACHINE] [varchar](50) NOT NULL,
[PASSWORD_HASH] [varchar](100) NOT NULL,
CONSTRAINT [PK_JQD_PASSWORD] PRIMARY KEY CLUSTERED
(
[USER_ID] ASC,
[INSTALL_MACHINE] ASC
)
DPAPI Decrypt and use Old-New Password Chain
using (JQD.XIPCommon.Entity.ImportExportXIP.ImportExportXIPDataContext ctx = new JQD.XIPCommon.Entity.ImportExportXIP.ImportExportXIPDataContext(_csImportExportXIPIntSec))
{
var q = from r in ctx.JQD_PASSWORDs
where r.INSTALL_MACHINE == Environment.MachineName &&
r.USER_ID == _TraderName
select new { r.PASSWORD, r.NEW_PASSWORD };
string nPWD=q.First().NEW_PASSWORD;
string oPWD=Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(q.First().PASSWORD ), null, DataProtectionScope.LocalMachine));
if (nPWD == string.Empty)
{
LoggingHelper.DoMsmqLogging("Trader Password retrieved successfully", "JQDAllocationService::GetTraderPassword", "Normal", "Info");
return oPWD;
}
else
{
LoggingHelper.DoMsmqLogging("Password change detected, updating password...", "JQDAllocationService::GetTraderPassword", "Normal", "Info");
nPWD=RijndaelSimple.Decrypt(nPWD, oPWD, oPWD, "SHA1", 1, "@1B2c3D4e5F6g7H8", 256);
JQD.XIPCommon.Entity.ImportExportXIP.JQD_PASSWORD pwd = new JQD.XIPCommon.Entity.ImportExportXIP.JQD_PASSWORD();
pwd.USER_ID = _TraderName;
pwd.PASSWORD =Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(nPWD), null, DataProtectionScope.LocalMachine));
pwd.INSTALL_MACHINE = Environment.MachineName ;
pwd.NEW_PASSWORD = "";
HashAlgorithm hash = new SHA1Managed();
pwd.PASSWORD_HASH = Convert.ToBase64String((hash.ComputeHash(Encoding.UTF8.GetBytes(pwd.PASSWORD))));
var q2 = (from a in ctx.JQD_PASSWORDs
where a.USER_ID == _TraderName &&
a.INSTALL_MACHINE == Environment.MachineName
select a);
ctx.JQD_PASSWORDs.DeleteAllOnSubmit(q2);
ctx.SubmitChanges();
ctx.JQD_PASSWORDs.InsertOnSubmit(pwd);
ctx.SubmitChanges();
LoggingHelper.DoMsmqLogging("Password update completed. will try login", "JQDAllocationService::GetTraderPassword", "Normal", "INfo");
return nPWD;
}
}
DPAPI encrypt post installation
string DPAPIEncrypt(string clearText)
{
return Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(clearText ), null, DataProtectionScope.LocalMachine));
}
private void SavePassword()
{
string MachineName = Environment.MachineName;
string cs = ConfigurationManager.ConnectionStrings["PasswordManagement.Properties.Settings.ImportExportXIPConnectionString"].ConnectionString;
using (ImportExportXIPDataContext ctx = new ImportExportXIPDataContext(cs)) // use integrated security
{
JQD_PASSWORD pwd = new JQD_PASSWORD();
pwd.USER_ID = tbUserID_Installation.Text;
pwd.PASSWORD = DPAPIEncrypt(tbPassword_Installation.Text);
pwd.INSTALL_MACHINE = MachineName;
pwd.NEW_PASSWORD = "";
HashAlgorithm hash = new SHA1Managed();
pwd.PASSWORD_HASH = Convert.ToBase64String((hash.ComputeHash(Encoding.UTF8.GetBytes(tbPassword_Installation.Text))));
var q = (from a in ctx.JQD_PASSWORDs
where a.USER_ID == tbUserID_Installation.Text &&
a.INSTALL_MACHINE == MachineName
select a);
ctx.JQD_PASSWORDs.DeleteAllOnSubmit(q);
ctx.SubmitChanges();
ctx.JQD_PASSWORDs.InsertOnSubmit(pwd);
ctx.SubmitChanges();
}
}
Change Password
private void btnChange_Click(object sender, EventArgs e)
{
string MachineName = Environment.MachineName;
string cs = ConfigurationManager.ConnectionStrings["PasswordManagement.Properties.Settings.ImportExportXIPConnectionString"].ConnectionString;
HashAlgorithm hash = new SHA1Managed();
string entered_pwd_hash = Convert.ToBase64String((hash.ComputeHash(Encoding.UTF8.GetBytes(tbOldPassword.Text))));
using (ImportExportXIPDataContext ctx = new ImportExportXIPDataContext(cs)) // use integrated security
{
var q = (from a in ctx.JQD_PASSWORDs
where a.USER_ID == cbUserID.SelectedValue.ToString() &&
a.PASSWORD_HASH==entered_pwd_hash
select a);
if (q.Count()==0)
{
MessageBox.Show("No machines use the old password entered. You may try to enter another old password");
WriteToLog("No machines use the old password entered, Therefore no change of password");
return;
}
if (!TestPassword(cbUserID.SelectedValue.ToString(), tbNewPassword.Text))
{
WriteToLog("New password is invalid. No change will be made.");
return;
}
foreach (JQD_PASSWORD pwd in q)
{
pwd.NEW_PASSWORD = RijndaelSimple.Encrypt(tbNewPassword.Text, tbOldPassword.Text, tbOldPassword.Text, "SHA1", 1, "@1B2c3D4e5F6g7H8", 256);
WriteToLog("New password saved for "+pwd.USER_ID+", "+pwd.INSTALL_MACHINE+" and will be picked up by installed services" );
}
ctx.SubmitChanges();
}
}
Rijndael Symmetric Encryption
public class RijndaelSimple
{
public static string Encrypt(string plainText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
public static string Decrypt(string cipherText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);
return plainText;
}
}
Sunday, February 15, 2009
LINQ Not In Query (Process[]).Contains does not work
Process[] psBeforeLogin = Process.GetProcessesByName("MxOrderGenerator");
MXXOMLib.MxEnumReturnCode ret = _MxgXOM.Login(TraderName, TraderPassword, XIPDBServer, "GMO_INTRADAY", MXXOMLib.MxEnumEncryptionMethod.MxeEncryptionMethodNone);
Process[] psAfterLogin = Process.GetProcessesByName("MxOrderGenerator");
var p = from rA in psAfterLogin
where !(from rB in psBeforeLogin select rB).Contains(rA)
select rA;
Console.WriteLine(p.Count());
count =2 always, it should be one.
As it turns out, cannot use Process in select. Can use ProcessID.
var p = from rA in psAfterLogin
where !(from rB in psBeforeLogin select rB.Id).Contains(rA.Id)
select rA;
Tuesday, February 10, 2009
SQL script to research CRD Derivative Trading Setup
select 'security', PARENT_SEC_ID, SEC_TYP_CD,* from CRD822Deriv..CSM_SECURITY where SEC_NAME like'%JQD%'
declare @SEC_ID int, @U_SEC_ID int
select @SEC_ID=10465198
select @U_SEC_ID=10012552
select 'sec_legs', PARENT_SEC_ID,SEC_TYP_CD,SWAP_LEG_IND,* from Deriv..CSM_SECURITY where PARENT_SEC_ID=@SEC_ID
select 'u_security', * from CSM_UNDERLYING_SECURITY where SEC_ID =@SEC_ID
select 'position', * from CS_POSITION where SEC_ID in (@SEC_ID ,@U_SEC_ID)
select 'sec_cust', * from CSM_Security_Cust where SEC_ID =@SEC_ID
select 'sec_parent_underlying',* from CSM_SECURITY where SEC_ID in (@SEC_ID ,@U_SEC_ID)
select 'order',* from TS_ORDER where SEC_ID in (@SEC_ID ,@U_SEC_ID)
select 'ord_alloc', * from TS_ORDER_ALLOC where ORDER_ID in (select ORDER_ID from TS_ORDER where SEC_ID in (@SEC_ID ,@U_SEC_ID))
select 'term',* from CSM_SECURITY_TERM where SEC_ID in (@SEC_ID ,@U_SEC_ID)
Monday, January 5, 2009
Link to Cloud Workflow Orchestration by NetEventRelayBinding
Cloud Workflow XAML:
Action -- http://www.jqd.com/cloud/IAlert/VIXAlert
[Namespace in WCF contract]/WCF Contract/MethodName
IMPORTANT --- MUST END W/O SLASH
Body --- <VIXAlert xmlns="http://www.jqd.com/cloud/"><msg>VIXUnder40</msg></VIXAlert>
<methodname xmlns="[Namespace]"><paramName>..
Url ---- sb://servicebus.windows.net/services/jqdsolution/anything/
Listener:
TransportClientEndpointBehavior cred =
new TransportClientEndpointBehavior();
cred.CredentialType = TransportClientCredentialType.UserNamePassword;
cred.Credentials.UserName.UserName = "jqdsolution";
cred.Credentials.UserName.Password = "xxxxxx";
NetEventRelayBinding nerb = new NetEventRelayBinding();
ServiceHost host = new ServiceHost(typeof(AlertListener),
new Uri("sb://servicebus.windows.net/services/jqdsolution/anything/")
);
host.AddServiceEndpoint("VIXAlertListener.IAlert", nerb, "sb://servicebus.windows.net/services/jqdsolution/anything/");
host.Description.Endpoints[0].Behaviors.Add(cred);
host.Open();
Console.WriteLine("VIX Listener Ready");
Console.ReadLine();
host.Close();
Handle firewall port blocking using HTTP mode:
ServiceBusEnvironment.OnewayConnectivity.Mode = ConnectivityMode.Http;
ServiceBusEnvironment.OnewayConnectivity.HttpModeRelayClientCredentials = cred;
ServiceBusEnvironment.OnewayConnectivity.HttpModeMessageBufferLocation = new Uri("http://servicebus.windows.net/services/jqdsolution/VIXAlertListener/" + Guid.NewGuid().ToString());
WCF Code:
[ServiceContract(Name = "IAlert", Namespace = "http://jqd.com/cloud/")]
public interface IAlert
{
[OperationContract(IsOneWay=true)]
void VIXAlert(string msg);
}
[ServiceBehavior(Name = "AlertListener", Namespace = "http://jqd.com/cloud/")]
public class AlertListener : IAlert
{
public void VIXAlert(string msg)
{
Console.WriteLine("Got Alert: " + msg);
}
}
Note that Namespace must match those in Cloud WF Action and NetEventRelayBinding
assume OneWay
Subscribe to:
Posts (Atom)