Wednesday, December 19, 2018

local SQL express connection string

        <add name="connection" connectionString="Data Source='.\SQLEXPRESS';Initial Catalog=market_data;Persist Security Info=True;User ID=sa;Password=Lord0701" providerName="System.Data.SqlClient" />
   

Thursday, November 8, 2018

Alpaca C#

https://github.com/alpacahq/alpaca-trade-api-csharp/blob/master/Alpaca.Markets.Tests/RestClientGeneralTest.cs

Thursday, October 18, 2018

AZure data sync using power shell

https://docs.microsoft.com/en-us/azure/sql-database/scripts/sql-database-sync-data-between-sql-databases

https://blogs.msdn.microsoft.com/datamigration/2018/02/08/automating-the-end-to-end-migration-of-sql-server-to-azure-sql-database-using-the-azure-database-migration-powershell-module/


alter table with primary key


drop index CIX_DT on dbo.[AAPL];

ALTER TABLE dbo.[AAPL] ADD CONSTRAINT [PK_dt] PRIMARY KEY CLUSTERED
(
    dt DESC
)

create table with primary key

The issue with this you have to make sure PK_KEY that KEY has to be unique

USE [market_data]
GO

/****** Object:  Table [dbo].[FLKS]    Script Date: 10/18/2018 6:57:24 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[FLKS](
 [Volume] [numeric](9, 0) NULL,
 [Open] [decimal](18, 4) NULL,
 [High] [decimal](18, 4) NULL,
 [Low] [decimal](18, 4) NULL,
 [Close] [decimal](18, 4) NULL,
 [WAP] [decimal](18, 4) NULL,
 [Count] [numeric](9, 0) NULL,
 [dt] [datetime] NOT NULL,
 [EMA9] [decimal](18, 4) NULL,
 [EMA10] [decimal](18, 4) NULL,
 [EMA20] [decimal](18, 4) NULL,
 [EMA21] [decimal](18, 4) NULL,
 [EMA50] [decimal](18, 4) NULL,
 [EMA100] [decimal](18, 4) NULL,
 [EMA200] [decimal](18, 4) NULL
) ON [PRIMARY]
GO

ALTER TABLE dbo.[FLKS] ADD CONSTRAINT [PK_FLKS] PRIMARY KEY CLUSTERED
(
    dt DESC
)

Tuesday, October 16, 2018

replicate local SQL to Azure SQL

You can to change log on the install SQLDataSyncAgent-2.0-x86-ENU.msi
And I know how to do it in local GPO
When installing a service to run under a domain user account, the account must have the right to logon as a service on the local machine. This logon right strictly applies only to the local computer and must be granted in the Local Security Policy.
Perform the following to edit the Local Security Policy of the computer you want to define the ‘logon as a service’ permission:
1.Logon to the computer with administrative privileges.
2.Open the ‘Administrative Tools’ and open the ‘Local Security Policy’
3.Expand ‘Local Policy’ and click on ‘User Rights Assignment’
4.In the right pane, right-click ‘Log on as a service’ and select properties.
5.Click on the ‘Add User or Group…’ button to add the new user.
6.In the ‘Select Users or Groups’ dialogue, find the user you wish to enter and click ‘OK’
7.Click ‘OK’ in the ‘Log on as a service Properties’ to save changes.
Notes:
•Ensure that the user which you have added above is not listed in the ‘Deny log on as a service’ policy in the Local Security Policy.

https://docs.microsoft.com/en-us/azure/sql-database/sql-database-get-started-sql-data-sync

C# multiple thread updating winform listbox items parallel processing

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IndicatorUpdator
{
    public partial class Form1 : Form
    {
        SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString);

        public Form1()
        {
            InitializeComponent();
            GetSymbols();
        }

        public void GetSymbols()
        {
            if (cnn.State == ConnectionState.Closed)
            {
                listBox1.Items.Insert(0, " try to open, connection stat:" + cnn.State.ToString());
                cnn.Open();
            }
            else
            {
                listBox1.Items.Insert(0, " already open, connection stat:" + cnn.State.ToString());

            }
            if (cnn.State == ConnectionState.Broken)
            {
                listBox1.Items.Insert(0, "***** broken connection stat:" + cnn.State.ToString());

            }

            listBox1.Items.Insert(0, " connection stat:" + cnn.State.ToString());
            String q1 = "select table_name from information_schema.tables";
            SqlCommand c1 = new SqlCommand(q1, cnn);

            using (var reader = c1.ExecuteReader())
            {
                while (reader.Read())
                {
                    //exist insert record
                    lbSymbol.Items.Insert(0,reader.GetString(0));
                }
            }


        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            System.Threading.Tasks.Parallel.For(0, lbSymbol.Items.Count, i =>
            {
                //Thread.Sleep(1000);
                //int j = i;
                //listBox1.Invoke(() => listBox1.Items.Insert(0, j));

              // below can access winform listbox control from different thread
                this.Invoke((MethodInvoker)delegate
               {
                   this.listBox1.Items.Insert(0, i);
               });
                //So stuff with i

                //Console.WriteLine("i: " + i);
            });
        }
    }
}

C# Parallel Programming

https://www.codeproject.com/Articles/71285/Introducing-NET-4-0-Parallel-Programming

C# more than one backgroundworker

https://stackoverflow.com/questions/10694271/c-sharp-multiple-backgroundworkers

private BackgroundWorker assignmentWorker;

    private void InitializeBackgoundWorkers() {
        assignmentWorker = new BackgroundWorker();
        assignmentWorker.DoWork += AssignmentWorkerOnDoWork;
        // ...
    }

    private void AssignmentWorkerOnDoWork( object sender, DoWorkEventArgs doWorkEventArgs ) {
        for( var f = 0; f < FilesToProcess; f++ ) {
            var fileProcessed = false;
            while( !fileProcessed ) {
                for( var threadNum = 0; threadNum < MaxThreads; threadNum++ ) {
                    if( !threadArray[threadNum].IsBusy ) {
                        Console.WriteLine( "Starting Thread: {0}", threadNum );

                        threadArray[threadNum].RunWorkerAsync( f );
                        fileProcessed = true;
                        break;
                    }
                }
                if( !fileProcessed ) {
                    Thread.Sleep( 50 );
                    break;
                }
            }
        }
    }

    private void button1_Click( object sender, EventArgs e ) {
        assignmentWorker.RunWorkerAsync();
    }

c# backgroundworker-

http://csharp-video-tutorials.blogspot.com/2014/03/backgroundworker-class-example-in.html

Monday, October 15, 2018

EMA calculation

https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages

http://investexcel.net/how-to-calculate-ema-in-excel/

SQL create index

CREATE CLUSTERED INDEX [IX_DT]
ON [Historical] ( [dt] DESC )

Saturday, October 13, 2018

C# sql connection string

            string connetionString = null;
            SqlConnection cnn;
            cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            try
            {
                cnn.Open();
                MessageBox.Show("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }



<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="connection" connectionString="Data Source='OFFICE\SQLEXPRESS';Initial Catalog=market_data;Persist Security Info=True;User ID=sa;Password=xxxxx" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
</configuration>

market data sql

https://www.mssqltips.com/sqlservertip/4467/using-sql-server-data-analysis-for-stock-trading-strategies/

Saturday, October 6, 2018

C# candlestick

https://stackoverflow.com/questions/1110105/financial-charts-in-net-best-library-to-display-a-live-streaming-1-min-stock-c

Thursday, October 4, 2018

C# app talk to app

https://blogs.windows.com/buildingapps/2015/09/22/using-cross-app-communication-to-make-apps-work-together-10-by-10/

Saturday, September 29, 2018

PC rescue instructions

https://kb.acronis.com/content/60131?build=13660&edition=0&gaID=234071240.931830426&language=1&sn=G2YLNMNR-8H23CHFF&winver=10.0

USB monitor not waking up

https://www.startech.com/faq/usb-video-adapters-windows-usb-sleep-mode

If the display connected through your USB display adapter does not wake up after your computer has been in extended hibernation, it is likely that Windows has automatically turned off the USB Root hub to save power.

The steps below outline how to configure the USB root hub to stay on during hibernation, to prevent this from happening.
Windows 8 / 10
  1. On your keyboard, press the Windows key + X and select Control Panel.
  2. Click Hardware and Sound, then click Power Options.
  3. Click Change plan settings for the plan you want to change.
  4. Click Change advanced power settings.
  5. Click the plus sign (+) next to “USB settings” and “USB selective suspend setting” to expand the options and change the setting to Disabled.
  6. Click OK to apply the setting.
Note: You may need to disconnect and re-connect your USB display adapter after applying these settings to re-establish the connection.

Saturday, September 15, 2018

filter lines in a text file


File.ReadLines("c:\test.txt").Where(x => !x.StartsWith("xYz--"));
File.ReadLines("c:\test.txt").AsParallel().Where(x => !x.StartsWith("xYz--"));

Thursday, September 6, 2018

How to insert picture to Google Sheet to have it show up in the cell

In the Google sheet cell type like following

=image("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsqXLO_m3Do-XLeNyV3lk06wHN73C3b2qTm98I1n4ZFl9Fde34GOevVgHuTK0PpRE6dr5gCG6o2DRAIE5fnoLlwUHxYcyowDNuzPYJzGu05qpjncjiAHFW9eVC5aYzMAhFrr4mpD6ruHMy/w945-h600-p-k-no-nu/door.JPG,4,300,300)")

URL must be have picture extension at the end. I just use Blogger posts which has the picture and copy the image link address

4,300,300)

4 must be used if need to specify width and height in pixels



Thursday, August 30, 2018

group windows folders in explorer quick access

Window Key + E to start Window's Explorer

Go to the folder you want to pin to Quick Access
Then right mouse click on Quick Access, and click on "Ping current folder to Quick Access"


Monday, June 11, 2018

visual studio team services TFS team foundation server service

https://mva.microsoft.com/en-US/training-courses/devops-with-visual-studio-team-services-and-team-foundation-server-16779?l=towF4fMzC_306218965

Thursday, May 17, 2018

How to: Specify Build Events (C#)

https://msdn.microsoft.com/en-us/library/ke5z92ks.aspx


o specify a build event

  1. In Solution Explorer, select the project for which you want to specify the build event.
  2. On the Project menu, click Properties.
  3. Select the Build Events tab.

copy /Y E:\WealthLab\PriceChannelBreakout\PriceChannelBreakout\bin\Debug\PriceChannelBreakout.dll "C:\Program Files\Fidelity Investments\Wealth-Lab Pro 6\Data\Strategies\GC\*.*"

Monday, May 7, 2018

numpy operations Udemy: Python for finance and trading alogrithms

arr
arr + arr
arr * arr
arr - arr
arr/arr
arr ** 3
arr + 100
np.sqrt(arr)
np.exp(arr)
np.max()
np.max(arr)
np.sin(arr)

numpy Udemy: Python for finance and trading alogrithms

conda install numpy

import numpy as np

NumPy array
#creating Numpy array

myList = [1,2,3]
np.array(myList)
x=np.array(myList)
type(x)

myMatrix=[[1,2,3],[4,5,6],[7,8,9]]

np.arange(0,5)
# range with step size
np.arange(0,11,2)

#float number
np.zeros(3)
np.zeros((3,3))
np.ones(3)
np.linespace
np.linspace(0,10,3)
np.eye(4)
np.random
np.random.rand(5,4)
np.random.randn(5,4)
np.random.randint(1,100)
np.random.randint(1,100,10)
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
arr.reshape(5,5)
arr.shape
arr.dtype

ranarr.max()
ranarr.argmax()

ranarr.min()


ranarr.argmin()

Udemy: Python for finance and trading alogrithms: syntax


https://www.anaconda.com/download/
download 3.6

https://conda.io/docs/user-guide/tasks/manage-environments.html

conda env create -f environment.yml

activate pyfinance

jupyter notebook

http://localhost:8888/?token=8353cd76ab1525e6aab4b0cf408cac74bf56a05589c68e71


Shift + enter : run
Shift + Tab : doc

define x='12'
x. +tab see all method

name="greg"
print("hi, {}".format(name))
number=12
print("hi, {}, no {}".format(name,number))

print("hi, {x}, {y}".format(y=x,x=no))

#nested list
nested =[1,2,["a","b"]]

#dictionary
d={'key':10, 'key2':'2nd'}
d['key2']

#tuple (can't change items)
t=(1,2,3)

#set
set([1,1])

import math

(1==1) and not (1==2)

# if and else has to on the same column, elif
if 1==2:
    print('hi')
elif 2==2:
    print('2')
else:
    print('3')

#for
seq=[1,2,3,4,5]
for jelly in seq:
   print(jelly)

#while
i=1
while(i<5):
 print('i={}'.format(i))
i=i+1

#range
range(5)

for i in range(0,20,2):
    print(i)

#function
def mF():
  print("hi")

def mF(p):
    print(p)

def mF(p='default'):
    print(p)

def mF(p='default'):
    return(p)

#lambda
lambda var:var*2

seq=[1,2,3]
list(map(lambda var:var*2,seq))

def is_even(num):
    return num%2 ==0
list(filter(is_even,seq))

list(filter(lambda num:num%2==0,seq))

#method
st.lower
st.upper
tweet=" go sp #cool"
tweet,split()
tweet.split('#')[1]
mylist=[1,2,3,4]
mylist.pop()
mylist.pop(1)
2 in mylist

Exercise
prince ** 0.5
import math
math.sqrt(price)

#task 2
stock_index[2:]

task#3
print("the {} is at {}".format(stock_index,price))

task#4
stock_info.keys()
stock_info['sp500']['yesterday']

stock_info['info'][1][2]

task#5
def source_finder(p):
        return  p.split("--")[-1]

def price_finder(p):
    return 'price' in p.lower()


task#6
def count_price(s):
   count = 0
   for word in s.lower().split():
        if 'price' in word:
            count = count + 1
   return count

def count_price(s)
     return s.lower().count('price')

task#7
def avg_price(s):
    return sum(s)/len(s)