Thursday, August 6, 2015

Get next number sequence in Axapta

//Axapta Job Code Snippet

static void GetNextNumber(Args _args)
{

NumberSeq                   numberSeq;
MyTempTable tempTable ;

;

ttsbegin;
numberSeq = NumberSeq::newGetNumFromCode("ItemId");

tempTable.clear();
tempTable.ItemId = numberSeq.num();
tempTable.insert();

ttscommit;

}

Wednesday, June 17, 2015

Sending email with Google AppEngine





import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

void email()
{
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
     
        String msgBody = name + "\n" + description + "\n" + email;

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("sender@email.com",
                    "sender"));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                    "recipientEmail", "recipientName"));
            msg.setSubject("Greetings");
            msg.setText("Hello");
            Transport.send(msg);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

}

Updating entity in Datastore

//https://cloud.google.com/appengine/docs/java/datastore/transactions

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;

void myTxn() {
 DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
 TransactionOptions options = TransactionOptions.Builder.withXG(true);
 Transaction txn = datastore.beginTransaction(options);

 Entity a = new Entity("EntityName");
 a.setProperty("Property", "Value");
 datastore.put(txn, a);

 txn.commit();
}

Monday, May 18, 2015

Populating an excel worksheet with a ADO recordset


Private Sub ImportTable(ByVal Rs As ADODB.Recordset, ByVal worksheetName As String, Optional ByVal appendMode As Boolean = False, Optional ByVal PrintFieldHeader As Boolean = True)

 
        'Date: 9 April, 2009
        'Author: David Tsang
 
        Dim ws As Worksheet
        Dim rowStart As Double
     
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
 
        If worksheetName = "$" Then
     
            Exit Sub
     
        End If
     
 
        Set ws = Worksheets(worksheetName)
             
        If appendMode = False Then
         
            ws.Cells.ClearContents
            rowStart = 1
     
        Else
             
            rowStart = ws.UsedRange.Rows.Count + 1
     
        End If
       
     
        With ws
     
          If PrintFieldHeader = True Then
     
            For x = 1 To Rs.Fields.Count
         
                .Cells(rowStart, x).Value = "'" & Rs.Fields(x - 1).Name
 
            Next
         
            rowStart = rowStart + 1
       
          End If
           
          With .Cells(rowStart, 1)
             
                numberOfRows = .CopyFromRecordset(Rs)
       
          End With
       
          .Columns.AutoFit
       
        End With
             
        Do Until ws.UsedRange.Rows.Count >= Rs.RecordCount
            DoEvents
        Loop

     
        Application.Calculation = xlCalculationAutomatic
             
End Sub

Wednesday, April 29, 2015

Getting stock price and exchange rate from Yahoo by Python



#download.py gets stock and exchange rates from Yahoo and then saves the data as a csv file in local drive.
#You may change the url and the filepath if necessary.
#Author: David Tsang 28 APR 2015

import urllib

#historical data
def downloadFile(symbol, filename):
    url = "http://real-chart.finance.yahoo.com/table.csv?s=" + symbol
    directory = "C:\\Python27\\Lib\\site-packages\\QSTK\\QSData\\Yahoo\\"
    print "Downloading " + symbol
    filepath = directory + filename + ".csv"
    urllib.urlretrieve (url, filepath)
    print "- Completed"

#latest quote
def quote(symbol, filepath):
    url = "http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.csv"
    #print "Downloading " + symbol
    urllib.urlretrieve (url, filepath)

#exchange rate
def exchrate(symbol, filepath):
    url = "http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol +"=X&f=sl1d1t1c1ohgv&e=.csv"
    print "Downloading " + symbol
    urllib.urlretrieve (url, filepath)

Friday, April 24, 2015

Consolidating excel worksheets by VB Script

'This VBS consolidates all worksheets in a excel file and outputs as a csv/text file

Dim conn
Dim Connstr
Dim rs, strSQL
Dim fieldIdx
Dim fileName
Dim recIdx
dim fs,fname
dim linetxt
dim separator
dim schemars
dim headerFlag

dim inputFile
dim outputFile
dim workDir

defaultDir = "C:\"
inputFile = "C:\input.xlsx"
outputFile = "output.csv"

Connstr ="Provider=MSDASQL.1;Persist Security Info=False;Extended Properties=""DSN=Excel Files;DBQ=" & inputFile &";DefaultDir=" & defaultDir &";DriverId=1046;MaxBufferSize=2048;PageTimeout=5;"""

Set conn = CreateObject("adodb.connection")
conn.Open Connstr

Set schemars = CreateObject("adodb.recordset")
Set schemars = conn.OpenSchema(20)

Set rs = CreateObject("ADODB.Recordset")

set fs=CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile(outputFile,true)

headerFlag = 0

'For all worksheets in the excel file
 Do until schemaRs.eof

'Process worksheet only. Worksheet name must be ended with a $ sign
'https://support.microsoft.com/en-us/kb/257819

if right(schemaRs(2),2) = "$'" then

strSQL = "select * from ["& schemaRs(2) & "]"

On Error resume next
set rs = conn.execute(strSQL)

if err.number = 0 then

if headerFlag = 0 then
fname.write printHeader(rs)
headerFlag = 1
end if

fname.write printData(rs, schemaRs(2))

rs.close

end if

On Error Goto 0

end if

schemaRs.movenext
 Loop

fname.Close
set fname=nothing
set fs=nothing

conn.Close

msgbox "Complete"

function printHeader(rs)

Dim fieldIdx
Dim returnVal
Dim separator

separator = vbtab

returnVal = "Index"

For fieldidx = 0 to rs.fields.count -1

returnVal = returnVal & separator & rs.fields(fieldidx).name

next

printHeader = returnVal

end function

function printData(rs, idx)

Dim returnVal
Dim linetxt
Dim separator

rs.movenext

Do until rs.eof

  'Add the worksheet name as index in the first column
linetxt = idx
separator = vbtab

for fieldidx = 0 to rs.fields.count -1

linetxt = linetxt & separator & rs(fieldIdx)

next

returnVal = returnVal & vbcrlf & lineTxt

rs.movenext

Loop

printData = returnVal

end function

Applying SMA10/20, SMA20/50 as trading signals

This is the comparison for results before and after applying SMA10/20 and SMA20/50 in the stock trader. Background Trading 3 stock ma...