Wednesday, October 21, 2020

Visual studio 2019 to visual studio online Azure DevOps

 After you create a project on the bottom right you can do add to source control





Tuesday, October 20, 2020

unix timestamp to C#

 public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )

{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}

Monday, October 19, 2020

Delete project from visual studio online

 https://docs.microsoft.com/en-us/azure/devops/organizations/projects/delete-project?view=azure-devops&tabs=browser

jason to C# class


 https://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;


namespace JasonTest

{

    class Program

    {

        static void Main(string[] args)

        {

            String dataIn = "{\"ev\":\"A\",\"sym\":\"AAPL\",\"v\":1267,\"av\":53480851,\"op\":119.96,\"vw\":118.8477,\"o\":118.8536,\"c\":118.84,\"h\":118.855,\"l\":118.84,\"a\":119.2689,\"z\":70,\"n\":1,\"s\":1603125023000,\"e\":1603125024000}";

            //var inCovJ = JsonConvert.DeserializeObject(dataIn);

            StockIn inCovJ = JsonConvert.DeserializeObject<StockIn>(dataIn);

            

            Console.WriteLine(inCovJ);

            Console.WriteLine();

        }

    }

}



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace JasonTest

{

    public class StockIn

    {

        public string ev { get; set; }

        public string sym { get; set; }

        public int v { get; set; }

        public int av { get; set; }

        public double op { get; set; }

        public double vw { get; set; }

        public double o { get; set; }

        public double c { get; set; }

        public double h { get; set; }

        public double l { get; set; }

        public double a { get; set; }

        public int z { get; set; }

        public long s { get; set; }

        public long e { get; set; }

    }

}


Thursday, September 24, 2020

Clickup app invite people

 on bottom left corner, click your Avtar, they you see invite, ...you can select invite by email and assign them member or admin

Friday, September 18, 2020

mplfinance and Alpaca charting working copy

#D:\test\p4\t4.py

import websocket

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from pyxtension.Json import Json

import numpy as np  

from datetime import datetime

import mplfinance as mpf

from matplotlib import style



def on_message(ws, message):

    #message = message.replace('[','').replace(']','')

    x = message.replace('[','').replace(']','')

    if x.find("sym") > 0:

        x = x.replace('[','').replace(']','')

        print (x)

        y = Json(x)

        #print(y.sym)

        open  = y.o

        print("open: ", open)

        close = y.c

        high = y.h

        low = y.l

        vw = y.vw

        volume = y.v

        timestamp = str(y.s)

        timestamp = timestamp[0:10]

        timestampEnd = str(y.e)

        timestampEnd = timestampEnd[0:10]

        dateBeg =  datetime.fromtimestamp(int(timestamp))

        dateEnd =  datetime.fromtimestamp(int(timestampEnd))

        global dfObj

        dfObj = dfObj.append({'Open':open, 'High':high, 'Low':low, 'Close':close, 'Volume':volume,'VW':vw,'DateBeg': dateBeg, 'Date': dateEnd }, ignore_index=True)

           

        print("close:",dfObj.Close)

        trows = len(dfObj.index)

        noRows = 9

        print("cnt:", trows)

        if trows > noRows:

            print (dfObj)

            dfObj = dfObj.set_index(pd.DatetimeIndex(dfObj['Date']))

            ax1.clear()

            ax2.clear()

            mpf.plot(dfObj,type='candle', ax=ax1,volume=ax2, block=False, mav=(9,21,50,200))

            plt.pause(3)

            print("passed fig ****************ROW > NO *******************************")

        elif trows == noRows:

            dfObj = dfObj.set_index(pd.DatetimeIndex(dfObj['Date']))

            print(dfObj)

            mpf.plot(dfObj,type='candle', ax=ax1,volume=ax2, block=False, mav=(9,21,50,200))

            plt.pause(3)

            print("passed fig ************** ROW = NO *********************************")


def on_error(ws, error):

    print(error)


def on_close(ws):

    print("### closed ###")

    #f.close


def on_open(ws):

    ws.send('{"action":"auth","params":"XXXX"}')

    ws.send('{"action":"subscribe","params":"A.AAPL"}')

    


#f = open("demofile.txt", "a")


#Set up plot

#fig = mpf.figure(figsize=(10,9))

fig = mpf.figure()

ax1 = fig.add_subplot(2,1,1,style='yahoo')

ax1 = fig.add_subplot(2,1,1)

ax2 = fig.add_subplot(3,1,3)


#ax1 = fig.add_subplot(1, 1, 1)

#fig, ax = plt.subplots()

#lines, = ax.plot([],[], 'o')

#Autoscale on unknown axis and known lims on the other

ax1.set_autoscaley_on(True)

#ax.set_xlim(self.min_x, self.max_x)

##Other stuff

ax1.grid()

#lt.tight_layout()

dfObj = pd.DataFrame(columns=['Open', 'High', 'Low','Close', 'Volume', 'VW', 'DateBeg', 'Date'])

#print("Empty Dataframe ", dfObj, sep='\n')

dfObj = dfObj.set_index(pd.DatetimeIndex(dfObj['Date']))


if __name__ == "__main__":

    # websocket.enableTrace(True)

    

    ws = websocket.WebSocketApp("wss://socket.polygon.io/stocks",

                              on_message = on_message,

                              on_error = on_error,

                              on_close = on_close)

    ws.on_open = on_open


    ws.run_forever()

Wednesday, September 16, 2020

“inconsistent use of tabs and spaces in indentation”

 https://stackoverflow.com/questions/5685406/inconsistent-use-of-tabs-and-spaces-in-indentation

It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:

  1. Choose Search -> Find... or press Ctrl + F
  2. Select the Replace tab
  3. In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
  4. In the field Find what : write \t
  5. In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
  6. Click on the button Replace All

How to replace Tabs with Spaces

  edit    flag 


Alpaca data stream

 # Be sure to pip install websocket-client

# Details: https://pypi.org/project/websocket-client/

import websocket
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyxtension.Json import Json
import numpy as np  
from datetime import datetime

def on_message(wsmessage):
    #message = message.replace('[','').replace(']','')
    x = message.replace('[','').replace(']','')
    if x.find("sym") > 0:
        x = x.replace('[','').replace(']','')
        print (x)
        y = Json(x)
        #print(y.sym)
        open  = y.open
        close = y.close
        high = y.high
        low = y.low
        vw = y.vw
        volumn = y.volumn
        timestamp = str(y.s)
        timestamp = timestamp[0:10]
        timestampEnd = str(y.e)
        timestampEnd = timestampEnd[0:10]
        dateBeg =  datetime.fromtimestamp(int(timestamp))
        dateEnd =  datetime.fromtimestamp(int(timestampEnd))
        global dfObj
        dfObj = dfObj.append({'Open':open'High':high, 'Low':low, 'Close':close, 'Volumn':volumn,'VW':vw,'Date': dateBeg, 'Date_end': dateEnd }, ignore_index=True)
        trows = len(dfObj.index)
        print("cnt:", trows)


def on_error(wserror):
    print(error)

def on_close(ws):
    #print("### closed ###")
    f.close

def on_open(ws):
    ws.send('{"action":"auth","params":"XXXX"}')
    ws.send('{"action":"subscribe","params":"A.AAPL"}')

f = open("demofile.txt""a")
dfObj = pd.DataFrame(columns=['Open''High''Low','Close''Volumn''VW''Date''Date_end'])
print("Empty Dataframe ", dfObj, sep='\n')
dfObj = dfObj.set_index(pd.DatetimeIndex(dfObj['Date']))

if __name__ == "__main__":
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://socket.polygon.io/stocks",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

Tuesday, September 15, 2020

python requirements.txt

 https://stackoverflow.com/questions/31684375/automatically-create-requirements-txt

Python Websocket Alpaca (code works if you put in the key)

 # Be sure to pip install websocket-client

# Details: https://pypi.org/project/websocket-client/


import websocket

import json

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt


def on_message(ws, message):

    with open('data.txt', 'a') as outfile:

        json.dump(message, outfile)

    print(message)

    


def on_error(ws, error):

print(error)


def on_close(ws):

#print("### closed ###")

    f.close


def on_open(ws):

ws.send('{"action":"auth","params":"XXXX"}')

ws.send('{"action":"subscribe","params":"A.AAPL"}')


f = open("demofile.txt", "a")

if __name__ == "__main__":

# websocket.enableTrace(True)

ws = websocket.WebSocketApp("wss://socket.polygon.io/stocks",

  on_message = on_message,

  on_error = on_error,

  on_close = on_close)

ws.on_open = on_open


ws.run_forever()

Monday, September 14, 2020

Python PIP not installed on VS code

 This occurs when broken pip. The broken pip caused by the failed upgrade can be fixed by running: "easy_install pip"

https://github.com/DamnWidget/anaconda/issues/762


Saturday, September 12, 2020

add_subplot mplfinance

 https://stackoverflow.com/questions/3584805/in-matplotlib-what-does-the-argument-mean-in-fig-add-subplot111

3

The add_subplot() method has several call signatures:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <-- since 3.1


Wednesday, September 9, 2020

jupeter notebook in VS Code

 https://www.youtube.com/watch?v=FSdIoJdSnig

https://github.com/Microsoft/vscode-python


Friday, September 4, 2020

Json to C#

 

https://youtu.be/CjoAYslTKX0

Visual Studio during debug execute few lines of test code in immediate window

 You can run a lot of things in the Immediate window (Debug >> Windows >> Immediate)

For example, you can run the following: System.IO.File.WriteAllText(@"c:\temp\blah.txt", "Hi there!");

https://stackoverflow.com/questions/384743/how-to-quickly-code-and-run-small-c-sharp-code



visual studio command window

 Use veiew => other windows => command window

Thursday, September 3, 2020

Plogon Python for Alpaca

 # Be sure to pip install websocket-client

# Details: https://pypi.org/project/websocket-client/

import websocket
import json
def on_message(wsmessage):
    with open('data.txt''a'as outfile:
        json.dump(message, outfile)
    print(message)
    

def on_error(wserror):
    print(error)

def on_close(ws):
    #print("### closed ###")
    f.close

def on_open(ws):
    ws.send('{"action":"auth","params":"XXXXX"}')
    ws.send('{"action":"subscribe","params":"A.AAPL"}')

f = open("demofile.txt""a")
if __name__ == "__main__":
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://socket.polygon.io/stocks",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    

    ws.run_forever()

Tuesday, September 1, 2020

Calculate Moving Average

   Decimal CalculateMovingAverage(DateTime day, int numDays)

        {

            int quantity = 0;

            Decimal total = 0.0M;

            DateTime firstDay = GetDateXPeriodsAgo(day, numDays);

            foreach (StockInfo data in _stockData)

            {

                if (data.Date >= firstDay && data.Date <= day)

                {

                    total += data.ClosingPrice;

                    quantity++;

                }

            }

            return total / quantity;

        }

Calculate Exponential Moving Average EMA

    Decimal CalculateExponentialMovingAverage(DateTime day, int numDays)

        {

            Decimal factor = 2.0M / (1.0M + (Decimal)numDays);

            DateTime firstDay = GetDateXPeriodsAgo(day, numDays);

            Decimal total = CalculateMovingAverage(firstDay, numDays);


            DateTime workingDay;

            for (int i = numDays; i >= 0; i--)

            {

                workingDay = GetDateXPeriodsAgo(day, i);

                foreach (StockInfo data in _stockData)

                {

                    if (data.Date == workingDay)

                    {

                        total = (total * (1.0M - factor)) + (data.ClosingPrice * factor);

                    }

                }

            }

            return total;

        }

Monday, August 31, 2020

Saturday, August 29, 2020

ema

 def calc_scores(price_dfdayindex=-1):

    '''Calculate scores based on the indicator and
    return the sorted result.
    '''
    diffs = {}
    param = 10
    for symbol in price_df.columns.levels[0]:
        df = price_df[symbol]
        if len(df.close.values) <= param:
            continue
        ema = df.close.ewm(span=param).mean()[dayindex]
        last = df.close.values[dayindex]
        diff = (last - ema) / last
        diffs[symbol] = diff

    return sorted(diffs.items(), key=lambda x: x[1])


http://straightcode.net/learn/system/algo_trading

Friday, August 28, 2020

json to sql server

 https://youtu.be/lI3WiAmDvTw

 https://polygon.io/sockets

// Stocks Aggregate:
{
    "ev": "AM",             // Event Type ( A = Second Agg, AM = Minute Agg )
    "sym": "MSFT",          // Symbol Ticker
    "v": 10204,             // Tick Volume
    "av": 200304,           // Accumulated Volume ( Today )
    "op": 114.04,           // Today's official opening price
    "vw": 114.4040,         // VWAP (Volume Weighted Average Price)
    "o": 114.11,            // Tick Open Price
    "c": 114.14,            // Tick Close Price
    "h": 114.19,            // Tick High Price
    "l": 114.09,            // Tick Low Price
    "a": 114.1314,          // Tick Average / VWAP Price
    "s": 1536036818784,     // Tick Start Timestamp ( Unix MS )
    "e": 1536036818784,     // Tick End Timestamp ( Unix MS )
}

tocks Cluster

wss://socket.polygon.io/stocks

Available Channels:
T.* Trades
Q.* Quotes
A.* Aggregate ( per second )
AM.* Aggregate ( per minute )


Thursday, August 27, 2020

TD authentication

 @AMER.OAUTHAP

chromedriver

 Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

C:\Users\greg chu\AppData\Roaming\Python\Python38\Scripts


Monday, August 17, 2020

cannot import name 'warnings' from 'matplotlib.dates'

 

cannot import name 'warnings' from 'matplotlib.dates' (C:\Users\greg chu\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\dates.py)


pip install matplotlib==3.2.2 --user
$ python
Python 2.7.6 (default, Jan 30 2014, 20:19:23) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.__version__
'1.1.1'

import matplotlib
matplotlib.__version__
https://community.backtrader.com/topic/981/importerror-cannot-import-name-min_per_hour-when-trying-to-plot/8