Musings

A random collection

Archive for April 2010

TECH: Mounting Windows Shares on Linux

  1. Make sure you have “samba-client” installed
  2. Now you can mount the Windows share on Linux as
    # cat cred.txt
    username=windowsusername
    password=hahahaha
    domain=windowsdomain
    # mount -t cifs -o 'credentials=cred.txt,uid=linuxuser,gid=linuxgrp' '//windowsmachine/sharename' /mywindowsmount
    # ls -l /mywindowsmount/
    

Written by curious

April 26, 2010 at 9:21 am

Posted in linux

TECH: Connecting to databases from Linux (using PHP, python etc)

Getting started

  1. Install Free TDS (freetds) and unixODBC
  2. Try connecting to the database (freetds comes with 2 clients: tsql, fisql). tsql is lower level tool. fisql is a replacement for isql (provided with unixODBC)
    tsql -S dbserver -U sa -P password -D MyOwnDB
    2> select * from SomeTable
    2> go
    
    fisql -S dbserver -U sa -P password
    1> use MyOwnDB
    1> go
    2> select * from SomeTable
    2> go
    
    fisql -S dbserver -U sa -P password -c ';'
    1> use MyOwnDB;
    2> select * from SomeTable;
    
  3. To try unixODBC, use test tool
  4. $ cat $HOME/.odbcinst.ini
    [FreeTDS]
    Description             = MS SQL Server Driver
    Driver          = /usr/lib/libtdsodbc.so.0
    Setup           = /usr/lib/libtdsS.so.2
    FileUsage               = 1
    UsageCount              = 1
    
    $ cat $HOME/.odbc.ini
    [SomeServerDSN]
    Driver = FreeTDS
    Description = Dev Server
    Server = serverhostname
    Trace = Yes
    Database = MyOwnDB
    
    $ isql SomeServerDSN dbuser dbpassword
    

Using Python (pyodbc) to connect to a SQL Server

  1. Install pyodbc
  2. Direct Connection (no DSN)
    import pyodbc
    cnxn = pyodbc.connect('DRIVER={FreeTDS};SERVER=serverhostname;DATABASE=MyOwnDB;UID=youruid;PWD=secret')
    cursor = cnxn.cursor()
    cursor.execute("select count(*) from SomeTable")
    row = cursor.fetchone()
    if row:
      print row
    else:
      print "No data"
    
  3. Use a DSN
    import pyodbc
    cnxn = pyodbc.connect('DSN=SomeServerDSN;UID=youruid;PWD=secret')
    cursor = cnxn.cursor()
    cursor.execute("select count(*) from SomeTable")
    row = cursor.fetchone()
    if row:
      print row
    else:
      print "No data"
    
  4. More help: code.google.com/p/pyodbc/wiki/GettingStarted

Using Django to connect to SQLServer

  1. Install django-pyodbc
    svn co http://django-pyodbc.googlecode.com/svn/trunk/ django-pyodbc
    export PYTHONPATH=$HOME/django-pyodbc
    
  2. Set up settings.py
    DATABASES = {
        'default': {
            'ENGINE': 'sql_server.pyodbc',
            'NAME': 'MyDBName',
            'USER': 'youuid',
            'PASSWORD': 'secret',
            'OPTIONS': {
              'driver': 'FreeTDS',
              'dsn': 'SomeServerDSN',
              },
        }
    }
    
  3. Test connection
    python manage.py shell
    >>> from django.db import *
    >>> c = connections['default'].cursor()
    >>> r = c.execute("select count(*) from SomeTable")
    >>> r = c.fetchone()
    >>> print r
    
  4. More help: django-pyodbc on Code.Google

Using PHP to connect to a SQL Server

  1. Install php, php-odbc, php-mssql
  2. Allow HTTPd to connect to database:
    setsebool -P httpd_can_network_connect_db 1
    
  3. Try out the following PHP script to connect to the database using ODBC
    <?php
    // connect to DSN MSSQL with a user and password
    print("Running to display traders<br/>\n");
    $connect = odbc_connect("Driver=FreeTDS;Server=SomeServerDSN", "DbUser", "Password") or die("couldn't connect");
    odbc_exec($connect, "use MyOwnDB");
    $result = odbc_exec($connect, "SELECT iField1, strField2 " .
            "FROM tblTable1");
    while(odbc_fetch_row($result)){
      print(odbc_result($result, "iField1") .
            ' ' . odbc_result($result, "strField2") . "<br>\n");
    }
    odbc_free_result($result);
    odbc_close($connect);
    ?>
    
  4. Now lets try using php-mssql
    <?php
    $myServer = "ServerHostName";
    $myUser = "DbUser";
    $myPass = "DbPassword";
    $myDB = "MyOwnDB";
    
    //connection to the database
    $dbhandle = mssql_connect($myServer, $myUser, $myPass)
      or die("Couldn't connect to SQL Server on $myServer");
    
    //select a database to work with
    $selected = mssql_select_db($myDB, $dbhandle)
      or die("Couldn't open database $myDB");
    
    //declare the SQL statement that will query the database
    $query = "SELECT iField1, strField2 ";
    $query .= "FROM tblTable1";
    
    //execute the SQL query and return records
    $result = mssql_query($query);
    
    $numRows = mssql_num_rows($result);
    echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
    
    print "<table>";
    print "<tr>";
    print "<th>ID</th>";
    print "<th>Name</th>";
    print "</tr>";
    
    //display the results
    while($row = mssql_fetch_array($result))
    {
    print "<tr>";
      echo "<td>" . $row["iField1"] . "</td>";
      echo "<td>" . $row["strField2"] . "</td>";
    print "</tr>";
    }
    print "</table>";
    //close the connection
    mssql_close($dbhandle);
    ?>
    

Connecting to MySQL from PHP

  1. Install php-mysql
  2. Run the following PHP script
    <?php
    $myServer = "theMySqlServer"; # myServer = "theMySqlServer:3306";
    $myUser = "mysql";
    $myPass = "dbPassword";
    $myDB = "dbName";
    
    //connection to the database
    $dbhandle = mysql_connect($myServer, $myUser, $myPass)
      or die("Couldn't connect to SQL Server on $myServer");
    
    //select a database to work with
    $selected = mysql_select_db($myDB, $dbhandle)
      or die("Couldn't open database $myDB");
    
    //declare the SQL statement that will query the database
    $query = "SELECT iField1, sField2 ";
    $query .= "FROM tblTable1 ";
    
    //execute the SQL query and return records
    $result = mysql_query($query);
    
    $numRows = mysql_num_rows($result);
    echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
    
    print "<table>";
    print "<tr>";
    print "<th>ID</th>";
    print "<th>Name</th>";
    print "</tr>";
    
    //display the results
    while($row = mysql_fetch_array($result))
    {
    print "<tr>";
      echo "<td>" . $row["iField1"] . "</td>";
      echo "<td>" . $row["sField2"] . "</td>";
    print "</tr>";
    }
    print "</table>";
    //close the connection
    mysql_close($dbhandle);
    ?>
    

Written by curious

April 21, 2010 at 10:39 am

Posted in databases, linux

TECH: Building Boost On Linux & Windows

Ensure that you have the following packages:

  1. zlib-devel bzip2-devel
  2. openmpi-devel
  3. python-devel
  4. libicu libicu-devel

Run the following:

./bootstrap.sh --prefix=/opt/boost --without-icu
./bjam install

On Windows

bootstrap.bat
.\bjam --prefix=c:\boost_1_43_0 --without-python --without-mpi install

.\bjam toolset=msvc --build-type=complete --libdir=C:\Boost\lib\i386 install

# specify Visual Studio version number to use a specific tool chain
.\bjam toolset=msvc-9.0 --build-type=complete --libdir=C:\Boost\lib\i386 install

Build 64-bit on Windows (32-bit)

bjam msvc architecture=x86 address-model=64 --prefix=c:\boost_1_44_0 --without-python --without-mpi stage
bjam msvc architecture=x86 address-model=64 --prefix=c:\boost_1_44_0 --without-python --without-mpi install

bjam.exe toolset=msvc --build-type=complete architecture=x86 address-model=64 --libdir=C:\Boost\lib\x64 install -j%NUMBER_OF_PROCESSORS%

To override Visual Studio Version, edit project-config.jam file

using msvc : 9.0 ;

Written by curious

April 20, 2010 at 1:22 pm

Posted in Boost

Tagged with

FIN: An Order

Attributes of an Order

  1. Instrument being traded (Future, Option)
  2. (Buy, Bid, Ask) Or (Sell, Offer)
  3. Order Type (Market, Limit, Market Limit, Market with Protection, Stop Limit, Stop with Protection)
  4. Qualifiers (Day, GTC, GTD, FAK, FOK)
  5. Quantity
  6. Display Quantity
  7. Minimum Quantity
  8. Price

Instrument

  1. Future/Option
  2. Underlying
  3. Strike
  4. Expiry Month, Year
    • F = January
    • G = February
    • H = March
    • J = April
    • K = May
    • M = June
    • N = July
    • Q = Aug
    • U = September
    • V = October
    • X = November
    • Z = December

Type of Orders

  1. Market Orders

    • Executed at whatever best price available in the market. It is possible that partial order is filled at one price and the remaining quantities are filled at another price.
  2. Limit Orders

    • Max purchase price (buyer)/min sale price (seller). A buy order will be executed at or below the limit price. Sell orders are executed at or above the limit price.
    • Partial order fills are possible. Any portion that gets matched is immediately executed.
    • Limit order remain on the book until: executed/canceled/expires.
  3. Market-Limit Orders

    • Starts executing at the best price in the market
    • If the order can only be filled partially, the remaining order becomes a “limit order” at that price.
  4. Market Orders with Protection

    • Filled within a pre-defined range of prices (protected range).
    • Protected range is current best price plus (or minus) “protection points” for a buy (or sell) order.
  5. Stop-limit Orders (Futures only)
  6. Stop Orders with Protection (Futures only)
  7. Cabinet Orders (Options only)
  8. Stop Spike Logic – prevent cascading stop orders from causing the market to trade outside of predefined values

Order Qualifiers

  1. Day [DEFAULT] – active only that trading day, automatically expire at the end of the day
  2. Good-Till-Canceled (GTC) – remain active until a) completely executed, b) canceled or c) when the instrument expires
  3. Good-Till-Date (GTD) – remain active until a) completely executed, b) canceled, c) when the instrument expires or d) expire at the specified date
  4. Fill-and-Kill (FAK) – Executed immediately against orders in the market (resting orders). If order is not filled completely, remaining balance is canceled. Can specify a minimum quantity, if not met then the order is canceled.
  5. Fill-or-Kill (FOK) – Fill immediately a) Completely or b) Nothing. Same as FAK (Min = Complete Order Qty)

Display Quantity/Maximum Show – control the amount that is shown to the market. May place an order of Quantity 1000/Display Quantity = 100, then only 1 lot of 100 is put in the market, when these 100 contracts are filled, next 100 will be released in the market. Minimum Quantity – entire order quantity is displayed in the market but will be executed immediately only if at least the minimum quantity can be filled. If the minimum quantity can not be filled, then the order is canceled immediately.

Type of contracts

  1. Futures – you pay nothing right now, but you are obligated to execute the trade on an underlying at the specified strike price, strike date
  2. (Outright) Options – you pay a premium and get a right to execute the trade if you choose to do so
  3. Option Spreads – a combination of multiple options. The spread legs and ratios of quantities are defined for an option spread..

Futures

(Outright) Options

Contract Name Syntax:

<Product Code> <Contract Month, Year> <Call or Put> <Strike Price>

Example: “GEH9 C9800” is “March 2009 Eurodollar Option 9800 Call”

Option Spreads

A spread is an instrument that consists of multiple futures or options contracts that are executed simultaneously when the spread is executed. On the other hand Outrights consist of a single future or option contract. Spread can be an “exchange recognized” spread type or a “user defined” spread. Various types of Option Spreads:

  1. Calendar (Horizontal (HO)/Diagonal (DG))
    • Call Horizontal (Buy 1 Call, Sell 1 Call at different expiries)
      • Sell 1xCall @ K1 Expiry T1
      • Buy 1xCall @ K1 Expiry T2
    • Put Horizontal
      • Sell 1xPut @ K1 Expiry T1
      • Buy 1xPut @ K1 Expiry T2
    • Call Diagonal (Different Strike, Different Expiry)
      • Buy 1xCall @ K1 Expiry T1
      • Sell 1xCall @ K2 Expiry T2
    • Put Diagonal
      • Buy 1xPut @ K1 Expiry T1
      • Sell 1xPut @ K2 Expiry T2
  2. Straddle (ST) (Buy 1 Call, Buy 1 Put at same strike, expiry)
    • Buy 1xCall @ K1 Expiry T1
    • Buy 1xPut @ K1 Expiry T1
  3. Strangle (SG) (Buy Call and Put for same Expiry but different Strikes)
    • Buy 1xCall @ K1 Expiry T1
    • Buy 1xPut @ K2 Expiry T1
  4. Vertical (VT)
    • Call
      • Buy 1xCall @ K1 Expiry T1
      • Sell 1xCall @K2 Expiry T1
    • Put
      • Buy 1xPut @ K1 Expiry T1
      • Sell 1xPut @ K2 Expiry T1
  5. Box (BX)
  6. Butterfly (BO)
  7. Conditional Curve (CC)
  8. Condor (CO)
  9. Double (DB)
  10. Horizontal Straddle (HS)
  11. Iron Condor (IC)
  12. Ratio 1×2 (12), 1×3 (13), 2×3 (23)
  13. Strip (SR)
  14. Risk Reversal (RR)
  15. Straddle Strips (SS)
  16. Xmas Tree (XT)
  17. 3-Way (3W)
  18. Iron Butterfly (IB)
  19. Jelly Roll (JR)
  20. Guts (GT)
  21. 3-way: Straddle v/Call (3C), Straddle v/Put (3P)

Future Spreads

FIX Messaging

Exchange/Market

Market States

  1. Market Enabled/Pre-Opening
  2. Pre-Opening/No-Cancel
  3. Continuous Trading
  4. Surveillance Intervention
  5. Maintenance Period

Market Makers

Order Types

  1. Mass Quote
  2. Quote Modify
  3. Quote Cancel
  4. Request for Quote
  5. Lead Market Maker Matching

FIX Messages

  1. Logon
  2. Heartbeat
  3. Test Request
  4. Resend Request
  5. Sequence Reset
  6. Logout
  7. Security Definition Request
  8. Security Definition Message
  9. New Order Single
  10. Execution Report(Confirmation/Ack)
  11. Execution Report(Fill Notice)
  12. Order Cancel/Replace Request (Modify)
  13. Order Cancel Request
  14. Order Cancel Reject
  15. Order Status Request
  16. Quote Request
  17. Quote Acknowledgment
  18. Quote Cancel
  19. Quote Cancel Acknowledgment

Message flows

Logon

Logon

Trader -> Exchange: Logon
note right of Exchange
    Good Logon Request
end note
Exchange -> Trader: Logon Confirmation
Exchange-> Trader: Test Reqeust
Trader -> Exchange: Heartbeat

Failed login

Trader -> Exchange: Logon
note right of Exchange
    Failed login
end note
Exchange -> Trader: Logout
destroy Exchange
A New Order

An Order

Trader -> Exchange: NewSingleOrder
Exchange -> Trader: ExecutionReport (Order Confirmation)
note over Exchange: a bit later
Exchange-> Trader: ExecutionReport(Partial Fill)
note over Trader: sometime later send a Modify
Trader -> Exchange: Order Cancel/Replace Request
Exchange -> Trader: ExecutionReport (Order Cancel/Replace Confirmation)
note over Exchange: a bit later
Exchange -> Trader: ExecutionReport (Fill)

CME Globex Platform

Runs markets for:

  1. CME
  2. CBOT
  3. NYMEX
  4. DME (Dubai)
  5. MGEX (Minneapolis Grain)
  6. KCBT (Kansas City Board of Trade)

Written by curious

April 14, 2010 at 3:03 pm

Posted in CME

TECH: Windows Setup

Replace hosts file with the file obtained from mvps.org. Note location of hosts file is determined by registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DataBasePath

Disable DNS Client service (run services.msc)

Install Firefox

Written by curious

April 2, 2010 at 12:10 pm

Posted in tech-tips