예제 #1
0
        DoTests
        (
            string usn
        )
        {
            // Method members
            bool      retCode;
            AuthToken token;

            // Demo mode information for the user
            LogHelper.Log("\r\nDEMO MODE");
            LogHelper.Log("---- ----");
            LogHelper.Log($"{Resx.GetString("TEST_HEADING")}");

            // Set the test mode
            TDAmerAPI.TestMode = true;

            // Initialize the database tables
            Broker.CreateDbTables();

            // Set the VERBOSITY LEVEL
            TDAmerAPI.verbosityLevel = Verbosity.Extensive;

            //*****************************************************************
            //
            // T E S T  # 1:  S E T T I N G S  F I L E
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #1:");
            LogHelper.Log($"{Resx.GetString("READING_SETTINGS_FILE")}....");
            Broker.settings = Settings.Read();

            // Were settings obtained?
            if (Broker.settings == null ||
                string.IsNullOrEmpty(Broker.settings.Currency) ||
                string.IsNullOrEmpty(Broker.settings.TdaAccountNum))
            {
                // NO: Error has been logged, exit with failure code
                LogHelper.Log($"{Resx.GetString("SETTINGS_FILE_ERROR")}....");
                return(false);
            }
            else
            {
                LogHelper.Log($"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("READING_SETTINGS_FILE")}.");
            }

            //*****************************************************************
            //
            // T E S T  # 2:  U S E R  A U T H E N T I C A T I O N
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #2:");
            LogHelper.Log($"{Resx.GetString("AUTHENTICATING_USER")}...");

            // The username is actually the client id, save it in settings
            Broker.settings.ClientId = usn;

            // Save the full path of the token data file
            Broker.tokenDataFile = Broker.WORKING_DIR + Broker.dataFile;

            // Initialize the connection configuration using the refresh token
            // (usn) and the client id obtained from the settings
            Broker.oAuthConfiguration = new TDAmeritradeConnectConfiguration(Broker.settings.ClientId);

            // Initialize the connection client with the configuration
            Broker.oAuthClient = new TDAmeritradeConnectClient(Broker.oAuthConfiguration);

            // Delete the token file
            if (File.Exists(Broker.tokenDataFile))
            {
                File.Delete(Broker.tokenDataFile);
            }

            // Get an authentication token
            token = GetAuthToken();

            // Auth token received?
            if (token != null)
            {
                LogHelper.Log($"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("TEST_AUTHENTICATION_AUTH_TOKEN")}");
            }
            else
            {
                LogHelper.Log(LogLevel.Error, $"{Resx.GetString("FAILURE").ToUpper()}: {Resx.GetString("TEST_AUTHENTICATION_FAILURE")}.");
                return(false);
            }

            // Valid TD Ameritrade account?
            AccountBalance balance = Broker.Account(Broker.settings.TdaAccountNum);

            if (balance == null)
            {
                // Log the error
                LogHelper.Log(LogLevel.Error, $"{Resx.GetString("FAILURE").ToUpper()}: {Resx.GetString("INVALID_TDA_ACCT_NUM")}.");
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 3:  R E F R E S H   A U T H E N T I C A T I O N
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #3:");
            LogHelper.Log($"{Resx.GetString("TEST_REFRESH_TOKEN_AUTH")}...");

            // Get another auth token, should be using refresh token now
            token = GetAuthToken();

            // Auth token received?
            if (token != null)
            {
                LogHelper.Log($"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("TEST_ACCESS_TOKEN_FROM_REFRESH")}.");
            }
            else
            {
                LogHelper.Log(LogLevel.Error, $"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("TEST_NO_ACCESS_TOKEN_FROM_REFRESH")}.");
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 4:  M A R K E T  H O U R S
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #4:");
            LogHelper.Log($"{Resx.GetString("GET_NYSE_HOURS")}....");

            bool isNYSEOpen = Broker.IsMarketOpen("EQUITY");

            // Print out results
            string open = isNYSEOpen ? Resx.GetString("OPEN").ToUpper() : Resx.GetString("NOT_OPEN").ToUpper();

            LogHelper.Log($"{Resx.GetString("CURRENT_UTC_TIME")} {DateTime.UtcNow}.");
            LogHelper.Log($"{Resx.GetString("THE_NYSE_IS")} {open}.");

            //*****************************************************************
            //
            // T E S T  # 5:  B R O K E R  T I M E
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #5:");
            LogHelper.Log($"{Resx.GetString("BROKER_TIME")}...");
            double?dServerTime;

            // Call the Broker.Time function and get the server time out
            int code = Broker.Time(out dServerTime);

            // Print the current time
            LogHelper.Log($"{Resx.GetString("CURRENT_UTC_TIME")} {DateTime.UtcNow}.");

            // Evaluate return code from Broker.Time
            if (code == 0)
            {
                LogHelper.Log($"{Resx.GetString("ERROR")}: {Resx.GetString("CONN_LOST")}.");
                return(false);
            }
            else if (code == 1)
            {
                LogHelper.Log($"{Resx.GetString("CONN_OK_MARKET_CLOSED")}.");
            }
            else
            {
                LogHelper.Log($"{Resx.GetString("CONN_OK_MARKET_OPEN")}.");
            }

            LogHelper.Log($"{Resx.GetString("SERVER_UTC_OLE")}: {dServerTime}.");
            LogHelper.Log($"{Resx.GetString("SERVER_UTC_CONVERTED")}: {DateTime.FromOADate((double)dServerTime)}.");

            // Get the server time and the current time
            DateTime currentTime = DateTime.UtcNow;
            DateTime serverTime  = DateTime.FromOADate((double)dServerTime);

            // Get the difference in the two times
            TimeSpan diffTime    = serverTime - currentTime;
            int      secondsDiff = Math.Abs(diffTime.Seconds);

            if (secondsDiff < 30)
            {
                LogHelper.Log($"{Resx.GetString("TEST_SERVER_TIME_SUCCESS")}.");
            }
            else
            {
                LogHelper.Log($"{Resx.GetString("TEST_SERVER_TIME_FAILURE")}.");
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 6:  A S S E T  S U B S C R I P T I O N
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #6:");
            LogHelper.Log($"{Resx.GetString("BROKER_ASSET")}...");

            // Use Microsoft
            string  symbol = "MSFT";
            TDAsset asset  = Broker.Asset(symbol);

            if (asset == null)
            {
                LogHelper.Log($"{Resx.GetString("TEST_ASSET_INFO_FAILURE")} {symbol}.");
                return(false);
            }

            // Subscribe to this asset
            Broker.Subscription(asset);

            // Is asset on subscription list
            if (Broker.subscriptionList.Count > 0 && Broker.subscriptionList[0].Symbol == symbol)
            {
                LogHelper.Log($"{Resx.GetString("TEST_ASSET_SUCCESS")} {symbol}.");
            }
            else
            {
                LogHelper.Log($"{Resx.GetString("TEST_ASSET_FAILURE")} {symbol}.");
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 7:  U P D A T E  A S S E T S  C S V  F I L E
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #7:");
            LogHelper.Log($"{Resx.GetString("UPDATING_ASSETS_CSV")}...");

            // Update the assets CSV fileU
            retCode = AssetsCSV.UpdateAssetsCSV();
            if (retCode)
            {
                LogHelper.Log($"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("UPDATING_ASSETS_CSV")}.");
            }
            else
            {
                LogHelper.Log($"{Resx.GetString("FAILURE").ToUpper()}: {Resx.GetString("UPDATING_ASSETS_CSV")}.");
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 8:  T R A D E  F I L E  S Y N C H R O N I Z A T I O N
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #8:");
            LogHelper.Log($"{Resx.GetString("TRADE_FILE_SYNCHRONIZATION")}...");

            // Update the assets CSV file
            retCode = Broker.Sync();
            if (retCode)
            {
                LogHelper.Log($"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("TRADE_FILE_SYNCHRONIZATION")}.");
            }
            else
            {
                LogHelper.Log($"{Resx.GetString("FAILURE").ToUpper()}: {Resx.GetString("TRADE_FILE_SYNCHRONIZATION")}.");
                return(false);
            }


            //*****************************************************************
            //
            // T E S T  # 9:  M A R K E T  B U Y / S E L L

            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #9:");
            LogHelper.Log($"{Resx.GetString("TEST_BUY_SELL_INFO")}");

            // The test symbol
            symbol = "GRPN";

            // Get information for
            TDAsset tdAsset = Broker.Asset(symbol);
            Trade   order   = null;

            // Was the information obtained for this asset?
            if (tdAsset != null)
            {
                // YES: Subscribe to this asset
                Broker.Subscription(tdAsset);

                // Is the NYSE Open?
                if (!Broker.IsMarketOpen("EQUITY"))
                {
                    // NO: BUY 1 share of tdAsset AT MARKET
                    order = PlaceOrder(tdAsset.Symbol, 2, 0, 0);
                    if (!GetOrderInfo(order))
                    {
                        return(false);
                    }

                    // SELL 1 share of tdAsset AT MARKET
                    PlaceOrder(tdAsset.Symbol, -12, 0, 0);
                    if (!GetOrderInfo(order))
                    {
                        return(false);
                    }
                }

                PlaceOrder(tdAsset.Symbol, 2, 1.50, 150);

                // Can always place LIMIT orders with outrageous limits so they can
                // be canceled immediately.

                // BUY 1 share of tdAsset AT LIMIT price (100% above current price)
                // Asset price should never get there, so order should pend and
                // easily be canceled.
                order = PlaceOrder(tdAsset.Symbol, 1, 0, tdAsset.Price * 2);
                if (!GetOrderInfo(order))
                {
                    return(false);
                }

                // SELL 1 share of tdAsset AT LIMIT price (100% above current
                // price) Asset price should never get there, so order should pend
                // and easily be canceled.
                order = PlaceOrder(tdAsset.Symbol, -12, 0, tdAsset.Price * 2);
                if (!GetOrderInfo(order))
                {
                    return(false);
                }
            }
            else
            {
                // Log the error
                LogHelper.Log($"{Resx.GetString("ERROR")}: {Resx.GetString("SUBSCRIBING_TO_ASSET")}.");

                // Return error status
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 10:  B R O K E R  H I S T O R Y
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #10:");
            LogHelper.Log($"{Resx.GetString("TEST_HISTORICAL_INFO")}");

            // Get the historical ticks for this asset
            Tick[] ticks = Broker.History(
                // Symbol
                "MSFT",

                // Start date
                DateTime.Parse("16 Feb 2019 14:00:00 GMT").ToOADate(),

                // End date
                DateTime.Parse("05 May 2020 18:00:00 GMT").ToOADate(),

                // Number of ticks per minute
                60,

                // Maximum number of ticks
                300
                );

            if (ticks.Count() == 300)
            {
                LogHelper.Log(LogLevel.Info, $"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("MSFT_PRICE_HISTORY")}.");
            }
            else
            {
                LogHelper.Log(LogLevel.Error, $"{Resx.GetString("FAILURE").ToUpper()}: {Resx.GetString("MSFT_PRICE_HISTORY")}.");
                return(false);
            }

            //*****************************************************************
            //
            // T E S T  # 11:  U S E R  A C C O U N T
            //
            //*****************************************************************
            LogHelper.Log($"\r\n{Resx.GetString("TEST")} #11:");
            LogHelper.Log($"{Resx.GetString("GET_USER_ACCT_INFO")}...");

            AccountBalance bal = Broker.Account(Broker.settings.TdaAccountNum);

            if (bal != null)
            {
                LogHelper.Log(LogLevel.Info, $"{Resx.GetString("SUCCESS").ToUpper()}: {Resx.GetString("RETRIEVE_ACCT_INFO")}{bal.AccountId}.");
            }
            else
            {
                LogHelper.Log(LogLevel.Error, $"{Resx.GetString("FAILURE").ToUpper()}: {Resx.GetString("RETRIEVE_ACCT_INFO")}{bal.AccountId}.");
                return(false);
            }

            // If testing made it here, all tests were successful
            return(true);
        }