using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Configuration;

using DJTRADEOBJLibESUNAP;

namespace TradeObjTest
{
    public partial class Form1 : Form
    {
        DJTRADEOBJLibESUNAP.TradeAppClass m_tradeApp;
        int m_nTradeDate = 0;
        int m_nStkConn = 0;
        int m_nFutConn = 0;
        int m_nHKConn = 0;
        bool m_bLoginOK = false;

        public Form1()
        {
            InitializeComponent();
        }

        void Init()
        {
            txtUID.Text = "16795856";     // 玉山測試機
            cbAID.Text = "目前無帳號";
            txtPwd.Text = "1qaz2wsx";
            AppSettingsReader ASReader = new AppSettingsReader();
            string strTradeDAS = "mvp.esunsec.com.tw/tradedas";
            strTradeDAS = ASReader.GetValue("TradeDas", typeof(string)).ToString();
            string strLoginServer = "登入主機位置:[" + strTradeDAS + "]";
            this.Text += "  " + strLoginServer ;

            InitTradeApp();

            int nErrCode = 0;
            string sErrMsg = "";
            int nRet = m_tradeApp.Init(strTradeDAS, out nErrCode, out sErrMsg);

            // LotSize example
            //string strLotSizeData = "0050=300|0028=200";
            //m_tradeApp.SetLotSizeData(strLotSizeData);

            DateTime dTDate = DateTime.Now;
            m_nTradeDate = dTDate.Year * 10000 + dTDate.Month * 100 + dTDate.Day;

            btnStkNewOrder.Enabled = false;
            btnStkModifyOrder.Enabled = false;
            btnStkQryOrder.Enabled = false;
            btnStkQryMatch.Enabled = false;
            btnStkQryPosition.Enabled = false;
            btnStkCancelOrder.Enabled = false;

            btnTFXNewOrder.Enabled = false;
            btnTFXModifyOrder.Enabled = false;
            btnTFXQryOrder.Enabled = false;
            btnTFXQryMatch.Enabled = false;
            btnTFXQryOI.Enabled = false;

            btnHKNewOrder.Enabled = false;
            btnHKModifyOrder.Enabled = false;
            btnHKQryOrder.Enabled = false;
            btnHKQryMatch.Enabled = false;
            btnHKQryPosition.Enabled = false;

            btnMixQuery.Enabled = false;

            UpdateConnectStatus();
        }

        void InitTradeApp()
        {
            m_tradeApp = new TradeAppClass();
            m_tradeApp.OnDataResponse += new _ITradeAppEvents_OnDataResponseEventHandler(m_tradeApp_OnDataResponse);
        }

        void m_tradeApp_OnDataResponse(int nEventID, string sResponseData)
        {
            switch (nEventID)
            {
                case 1: // 主動回報 連線狀態
                    this.BeginInvoke((MethodInvoker)delegate()
                    {
                        SetConnectStatus(sResponseData);
                    });
                    break;
                
                //20141209 alan test
                //case 10: //商品檔 直接載在本機端
                //    string sMSN1 = txtMSN.Text;
                //    if (sMSN1.Length > 0)
                //        sMSN1 += "\r\n";
                //    sMSN1 += sResponseData;
                //    txtMSN.Text = sMSN1;
                //    break;
                case 100: // 主動回報
                    this.BeginInvoke((MethodInvoker)delegate()
                    {
                        string sMSN = txtMSN.Text;
                        if (sMSN.Length > 0)
                            sMSN += "\r\n";
                        sMSN += sResponseData;
                        txtMSN.Text = sMSN;
                    });
                    break;

                case 101: // 下單 回傳(非同步)
                case 102: // 交易查詢 回傳(非同步)
                case 103: // 帳務查詢 回傳(非同步)
                    this.BeginInvoke((MethodInvoker)delegate()
                    {
                        txtResult.Text = sResponseData.Replace(">", ">\r\n");
                    });
                    break;
            }
        }

        void SetConnectStatus(string sData)
        {
            string[] arConn = sData.Split(',');

	        if (arConn.Length >= 2)
	        {
                int nConn = Int32.Parse(arConn[1]);
		        switch (Int32.Parse(arConn[0]))
		        {
		        case 1: // 證券
			        m_nStkConn = nConn;
			        break;
		        case 2: // 期權
			        m_nFutConn = nConn;
			        break;
		        case 3: // 複委託
			        m_nHKConn = nConn;
			        break;
		        }

		        UpdateConnectStatus();
	        }
        }

        void UpdateConnectStatus()
        {
            string sConnStatus = string.Format("連線狀態:\r\n證券: {0}\r\n期權: {1}\r\n複委託: {2}",
		        (m_nStkConn == 0) ? "" : "已連線",
		        (m_nFutConn == 0) ? "" : "已連線",
		        (m_nHKConn == 0) ? "" : "已連線");
            txtConnStatus.Text = sConnStatus;
        }

        void Fini()
        {
            try
            {
                m_tradeApp.Fini();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                MessageBox.Show(ex.Message);

                Application.Exit();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                Init();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                MessageBox.Show(ex.Message);

                Application.Exit();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Are you sure want to quit?", "關閉程式", MessageBoxButtons.YesNo)
                == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Fini();
        }

        private void SetAccountList()
        {
            cbACCOUNT.Items.Clear();
            STKAccount.Items.Clear();
            TFXAccount.Items.Clear();
            HKAccount.Items.Clear();
            int nCount = m_tradeApp.GetAccountCount();

            int i = 0;
            for (i = 0; i < nCount; i++)
            {
                string AccountData = m_tradeApp.GetAccount(i);
                AccountData = AccountData.Trim("<>".ToCharArray());
                cbACCOUNT.Items.Add(AccountData);

                string[] arField = AccountData.Split('|');
                if (arField.Length >= 4)
                {
                    string[] arAccID = arField[0].Split('=');
                    string[] arAccName = arField[1].Split('=');
                    string[] arUID = arField[2].Split('=');
                    string[] arType = arField[3].Split('=');

                    int nAccType = Int32.Parse(arType[1]);
                    switch (nAccType)
                    {
                        case 1: // 證券
                            STKAccount.Items.Add(arAccName[1] + "|" + arAccID[1]);
                            break;
                        case 2: // 期權
                            TFXAccount.Items.Add(arAccName[1] + "|" + arAccID[1]);
                            break;
                        case 3: // 複委託
                            HKAccount.Items.Add(arAccName[1] + "|" + arAccID[1]);
                            break;
                    }
                    ALLAccount.Items.Add(arAccName[1] + "|" + arAccID[1]);
                }
            }

            if (cbACCOUNT.Items.Count > 0)
                cbACCOUNT.SelectedIndex = 0;
            if (STKAccount.Items.Count > 0)
                STKAccount.SelectedIndex = 0;
            if (TFXAccount.Items.Count > 0)
                TFXAccount.SelectedIndex = 0;
            if (HKAccount.Items.Count > 0)
                HKAccount.SelectedIndex = 0;
            if (ALLAccount.Items.Count > 0)
                ALLAccount.SelectedIndex = 0;
        }

        private string GetAccountString(string Type)
        {
            if (Type == "STK")
            {
                string[] arArgs = STKAccount.Text.Split('|');
                return (arArgs.Length > 1) ? arArgs[1] : "";
            }
            if (Type == "TFX")
            {
                string[] arArgs = TFXAccount.Text.Split('|');
                return (arArgs.Length > 1) ? arArgs[1] : "";
            }
            if (Type == "HK")
            {
                string[] arArgs = HKAccount.Text.Split('|');
                return (arArgs.Length > 1) ? arArgs[1] : "";
            }
            if (Type == "ALL")
            {
                string[] arArgs = ALLAccount.Text.Split('|');
                return (arArgs.Length > 1) ? arArgs[1] : "";
            }
            return "";
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            int nErrCode = 0;
            string sErrMsg = "";
            try
            {
               
                if (cbAID.Items.Count <= 0)
                {
                    MessageBox.Show("請查詢帳號");
                    return;
                }
                 
                //測試
                /*
               cbAID.Text = "88440621317";
               txtPwd.Text = "baby1225";
                */

                if (m_tradeApp.Login(cbAID.Text, txtPwd.Text, out nErrCode, out sErrMsg) != 0)
                {
                    btnLogin.Enabled = false;
                    SetAccountList();

                    if (STKAccount.Items.Count > 0)
                    {
                        btnStkNewOrder.Enabled = true;
                        btnStkModifyOrder.Enabled = true;
                        btnStkQryOrder.Enabled = true;
                        btnStkQryMatch.Enabled = true;
                        btnStkQryPosition.Enabled = true;
                        btnStkCancelOrder.Enabled = true;
                    }

                    if (TFXAccount.Items.Count > 0)
                    {
                        btnTFXNewOrder.Enabled = true;
                        btnTFXModifyOrder.Enabled = true;
                        btnTFXQryOrder.Enabled = true;
                        btnTFXQryMatch.Enabled = true;
                        btnTFXQryOI.Enabled = true;
                    }

                    if (HKAccount.Items.Count > 0)
                    {
                        btnHKNewOrder.Enabled = true;
                        btnHKModifyOrder.Enabled = true;
                        btnHKQryOrder.Enabled = true;
                        btnHKQryMatch.Enabled = true;
                        btnHKQryPosition.Enabled = true;
                    }

                    if (ALLAccount.Items.Count > 0)
                    {
                        btnMixQuery.Enabled = true;
                    }

                    MessageBox.Show("登入成功");
                    m_bLoginOK = true;
                }
                else
                {
                    MessageBox.Show(string.Format("登入失敗:{0}", sErrMsg));
                }
            }
            catch(Exception)
            {
                MessageBox.Show("登入失敗");
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (!m_bLoginOK)
            {
                MessageBox.Show("請先登入");
                return;
            }

            if (m_tradeApp.Connect() != 0)
            {
                btnConnect.Enabled = false;
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            m_tradeApp.Disconnect();

            m_nStkConn = m_nFutConn = m_nHKConn = 0;
            btnConnect.Enabled = true;

            UpdateConnectStatus();
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            m_tradeApp.Logout(txtUID.Text);

            btnLogin.Enabled = true;

            cbACCOUNT.Items.Clear();
            cbACCOUNT.Text = "";

            STKAccount.Items.Clear();
            STKAccount.Text = "";

            TFXAccount.Items.Clear();
            TFXAccount.Text = "";

            HKAccount.Items.Clear();
            HKAccount.Text = "";

            ALLAccount.Items.Clear();
            ALLAccount.Text = "";

            cbAID.Items.Clear();
            cbAID.Text = "目前無帳號";

            btnStkNewOrder.Enabled = false;
            btnStkModifyOrder.Enabled = false;
            btnStkQryOrder.Enabled = false;
            btnStkQryMatch.Enabled = false;
            btnStkQryPosition.Enabled = false;
            btnStkCancelOrder.Enabled = false;


            btnTFXNewOrder.Enabled = false;
            btnTFXModifyOrder.Enabled = false;
            btnTFXQryOrder.Enabled = false;
            btnTFXQryMatch.Enabled = false;
            btnTFXQryOI.Enabled = false;

            btnHKNewOrder.Enabled = false;
            btnHKModifyOrder.Enabled = false;
            btnHKQryOrder.Enabled = false;
            btnHKQryMatch.Enabled = false;
            btnHKQryPosition.Enabled = false;

            btnMixQuery.Enabled = false;
            m_bLoginOK = false;
        }

        private void btnClearResult_Click(object sender, EventArgs e)
        {
            txtResult.Text = "";
        }

        private void btnClearMSN_Click(object sender, EventArgs e)
        {
            txtMSN.Text = "";
        }

        #region STOCK
        private void btnStkNewOrder_Click(object sender, EventArgs e)
        {
	        //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("STK");
            int nTT = GetSTKTT();
	        int nOT = 0;
            int nBS = GetSTKBS();    // 1: 買進/ 2: 賣出
	        string szStockID = txtStockID.Text;
            if (!IsNumber(txtQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtQty.Text);
	        string szPrice = txtPrice.Text;
            //if (szPrice.Length == 0 || szPrice == "0")
            //{
            //    szPrice = "0";
            //    nPT = 1;
            //}
	        string szBroker = "";
	        int nPayType = 0;
            int nPreOrder = STKCheckPreOrder.Checked ? 1 : 0;

            int nPT = GetSTKPT(); //0: 限價/ 1:漲停/ 2:跌停/ 3:平盤/ 4:市價

            string sCond = GetSTKCond(); //0:ROD,1:FOK,2:IOC
            //string strResult = m_tradeApp.Stock_NewOrder(szAccountID, m_nTradeDate, nTT, nOT, nBS, szStockID, nQty, nPT, szPrice, szBroker, nPayType, nPreOrder);

            string strResult = m_tradeApp.Stock_NewOrder(szAccountID, m_nTradeDate, nTT, nOT, nBS, szStockID, nQty, nPT, szPrice, szBroker, nPayType, nPreOrder, sCond);

            if (strResult != null && strResult.Length > 0)
		        MessageBox.Show(strResult);
        }

        private void btnStkModifyOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("STK");
            int nTT = GetSTKTT();
            int nOT = 0;
            string szOID = txtOID.Text;
            string szOrderNo = txtOrderNo.Text;
            int nBS = GetSTKBS();    // 1: 買進/ 2: 賣出
            if (!IsNumber(txtQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtQty.Text);

            if (!IsNumber(txtQCurrent.Text))
            {
                MessageBox.Show("請輸入數量 (QCurrent)");
                return;
            }
            int nQCurrent = Convert.ToInt32(txtQCurrent.Text);
            int nQMatch = 0;
            if (IsNumber(txtQMatch.Text))
            {
                nQMatch = Convert.ToInt32(txtQMatch.Text);
            }

            int nPreOrder = STKCheckPreOrder.Checked ? 1 : 0;

            string sNewPrice = txtNewPrice.Text; //改價價格
            string szNewPT = GetSTKNewPT(); //新價位別(0: 限價/ 1:漲停/ 2:跌停/ 3:平盤/ 4:市價) 
            int bChangePrice = ChangePriceCheckBox.Checked ? 1 : 0; //是否改價 
            string szNewCond = GetSTKNewCond();  // 新委託方式 (0: ROD, 1: FOK, 2: IOC) 
            string szCond = GetSTKCond(); //0:ROD,1:FOK,2:IOC


            //string strResult = m_tradeApp.Stock_ModifyOrder(szAccountID, m_nTradeDate, nTT, nOT,
            //    szOID, szOrderNo, txtStockID.Text, nBS, nQty, nQCurrent, nQMatch, nPreOrder);

            string strResult = m_tradeApp.Stock_ModifyOrder(szAccountID, m_nTradeDate, nTT, nOT,
                  szOID, szOrderNo, txtStockID.Text, nBS, nQty, nQCurrent, nQMatch, nPreOrder, sNewPrice, szNewPT, bChangePrice, szNewCond, szCond);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnStkCancelOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("STK");
            int nTT = GetSTKTT();
            int nOT = 0;
            string szOID = txtOID.Text;
            string szOrderNo = txtOrderNo.Text;
            int nBS = GetSTKBS();    // 1: 買進/ 2: 賣出
            if (!IsNumber(txtQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtQty.Text);

            if (!IsNumber(txtQCurrent.Text))
            {
                MessageBox.Show("請輸入數量 (QCurrent)");
                return;
            }
            int nQCurrent = Convert.ToInt32(txtQCurrent.Text);
            int nQMatch = 0;
            if (IsNumber(txtQMatch.Text))
            {
                nQMatch = Convert.ToInt32(txtQMatch.Text);
            }

            int nPreOrder = STKCheckPreOrder.Checked ? 1 : 0;

            string szPrice = txtPrice.Text;
            int nPT = GetSTKPT();

            string szCond = GetSTKCond(); //0:ROD,1:FOK,2:IOC

            string strResult = m_tradeApp.Stock_CancelOrder(szAccountID, m_nTradeDate, nTT, nOT,
                szOID, szOrderNo, txtStockID.Text, nBS, nQty, nQCurrent, nQMatch, nPreOrder,szPrice ,nPT, szCond);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnStkQryOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("STK");
            int nForceQuery = STKCheckForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.Stock_QueryOrder(szAccountID, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnStkQryMatch_Click(object sender, EventArgs e)
        {
            //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("STK");
            int nForceQuery = STKCheckForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.Stock_QueryMatch(szAccountID, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnStkQryPosition_Click(object sender, EventArgs e)
        {
            //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("STK");
            int nForceQuery = STKCheckForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.Stock_QueryPosition(szAccountID, m_nTradeDate, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private int GetSTKBS()
        {
            int nBS = 2;
            if (cbSTK_BS.SelectedIndex == 0 || cbSTK_BS.SelectedIndex == 1)
            {
                nBS = cbSTK_BS.SelectedIndex + 1;
            }
            return nBS;
        }

        private int GetSTKTT()
        {
            if (cbSTK_TT.SelectedIndex == 0 || cbSTK_TT.SelectedIndex == 1 || cbSTK_TT.SelectedIndex == 2)
            {
                return cbSTK_TT.SelectedIndex;
            }
            return 0;
        }

        private int GetSTKPT()
        {
            if (cbSTK_PT.SelectedIndex == 0 || cbSTK_PT.SelectedIndex == 1 || cbSTK_PT.SelectedIndex == 2 || cbSTK_PT.SelectedIndex == 3 || cbSTK_PT.SelectedIndex == 4)
            {
                return cbSTK_PT.SelectedIndex;
            }
            return 0;
        }

        private string GetSTKNewPT()
        {
            if (cbSTK_NewPT.SelectedIndex == 0 || cbSTK_NewPT.SelectedIndex == 1 || cbSTK_NewPT.SelectedIndex == 2 || cbSTK_NewPT.SelectedIndex == 3 || cbSTK_NewPT.SelectedIndex == 4)
            {
                return Convert.ToString(cbSTK_NewPT.SelectedIndex);
            }
            return "0";
        }

        private string GetSTKCond()
        {
            if (cbSTK_Cond.SelectedIndex == 0 || cbSTK_Cond.SelectedIndex == 1 || cbSTK_Cond.SelectedIndex == 2)
            {
                return Convert.ToString(cbSTK_Cond.SelectedIndex);
            }
            return "0";
        }
        private string GetSTKNewCond()
        {
            if (cbSTK_NewCond.SelectedIndex == 0 || cbSTK_NewCond.SelectedIndex == 1 || cbSTK_NewCond.SelectedIndex == 2)
            {
                return Convert.ToString(cbSTK_NewCond.SelectedIndex);
            }
            return "0";
        }



        #endregion

        #region FutOpt
        private void btnTFXNewOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "15000-3314559";
            string szAccountID = GetAccountString("TFX");
            int nTT = GetTFXType();    // 期權商品類型 (0:期貨, 1:選擇權)
            string strTradeID1 = txtTFXTradeID.Text;
            int nBS1 = GetTFXBS();   // 買賣別 (1: 買進/ 2: 賣出/ 3:超買/ 4:超賣 (3/4 for 興櫃))
            int nPT = 0;    // PT (0:限價, 1:漲停, 2:跌停, 3:平盤, 4:市價, 5:長效單)
            string strPrice = txtTFXPrice.Text;
            if (strPrice.Length == 0)
            {
                strPrice = "0";
                nPT = 4;
            }

            if (!IsNumber(txtTFXQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtTFXQty.Text);
            int nOffset = 0;    // 倉別(Offset) 0:新倉, 1:平倉, 2:自動, 4:當沖
            int nCond = 0;      // 委託條件 (0:ROD, 1:FOK, 2:IOC)
            string strTradeID2 = "";
            int nBS2 = 0;
            int nPreOrder = TFXCheckPreOrder.Checked ? 1 : 0; ;  // 1: 預約單/ 0:盤中單

            string strResult = m_tradeApp.FutOpt_NewOrder(szAccountID, m_nTradeDate, nTT, strTradeID1, nBS1,
                                nPT, strPrice, nQty, nOffset, nCond, strTradeID2, nBS2, nPreOrder);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnTFXModifyOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "15000-3314559";
            string szAccountID = GetAccountString("TFX");
            int nType = 0;				// 0:改量, 1:刪單, 2:改價
            string szOID = txtTFXOID.Text;
            string szOrderNo = txtTFXOrderNo.Text;
            if (!IsNumber(txtTFXQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtTFXQty.Text);

            int nTT = GetTFXType();    // 期權商品類型 (0:期貨, 1:選擇權)

            if (!IsNumber(txtTFXQCurrent.Text))
            {
                MessageBox.Show("請輸入數量 (QCurrent)");
                return;
            }
            int nQCurrent = Convert.ToInt32(txtTFXQCurrent.Text);

            int nQMatch = 0;
            if (IsNumber(txtTFXQMatch.Text))
            {
                nQMatch = Convert.ToInt32(txtTFXQMatch.Text);
            }
            int nPreOrder = TFXCheckPreOrder.Checked ? 1 : 0;
            int nNewPT = 1;				// 0:限價, 1:漲停, 2:跌停, 3:平盤, 4:市價, 5:長效單
            string strNewPrice = "0";
            int nNewCond = 0;			// 0:ROD, 1:FOK, 2:IOC

            string strTradeID1 = txtTFXTradeID.Text;
            string strTradeID2 = "";

            int nBS1 = GetTFXBS();
            int nBS2 = 0;
            int nCond = 0;
            int nOffSet = 0;

            string strResult = m_tradeApp.FutOpt_ModifyOrder(szAccountID, nType, m_nTradeDate, szOID,
                                szOrderNo, nQty, nTT, nQCurrent, nQMatch, nPreOrder, nNewPT, strNewPrice, nNewCond,
                                strTradeID1, strTradeID2, nBS1, nBS2, nCond, nOffSet,1,"");

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnTFXCancelOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "15000-3314559";
            string szAccountID = GetAccountString("TFX");
            string szOID = txtTFXOID.Text;
            string szOrderNo = txtTFXOrderNo.Text;
            if (!IsNumber(txtTFXQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtTFXQty.Text);

            int nTT = GetTFXType();    // 期權商品類型 (0:期貨, 1:選擇權)

            if (!IsNumber(txtTFXQCurrent.Text))
            {
                MessageBox.Show("請輸入數量 (QCurrent)");
                return;
            }
            int nQCurrent = Convert.ToInt32(txtTFXQCurrent.Text);

            int nQMatch = 0;
            if (IsNumber(txtTFXQMatch.Text))
            {
                nQMatch = Convert.ToInt32(txtTFXQMatch.Text);
            }
            int nPreOrder = TFXCheckPreOrder.Checked ? 1 : 0;

            string strTradeID1 = txtTFXTradeID.Text;
            string strTradeID2 = "";

            int nBS1 = GetTFXBS();
            int nBS2 = 0;
            int nCond = 0;
            int nOffSet = 0;

            string strResult = m_tradeApp.FutOpt_CancelOrder(szAccountID, m_nTradeDate, szOID,
                                szOrderNo, nQty, nTT, nQCurrent, nQMatch, nPreOrder,
                                strTradeID1, strTradeID2, nBS1, nBS2, nCond, nOffSet);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnTFXQryOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "15000-3314559";
            string szAccountID = GetAccountString("TFX");
            int nTT = GetTFXType();    // 期權商品類型 (0:期貨, 1:選擇權)
            int nForceQuery = TFXCheckForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.FutOpt_QueryOrder(szAccountID, nTT, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnTFXQryMatch_Click(object sender, EventArgs e)
        {
            //string szAccountID = "15000-3314559";
            string szAccountID = GetAccountString("TFX");
            int nForceQuery = TFXCheckForceQuery.Checked ? 1 : 0;
            nForceQuery = 0;
            string strResult = m_tradeApp.FutOpt_QueryMatch(szAccountID, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnTFXQryOI_Click(object sender, EventArgs e)
        {
            //string szAccountID = "15000-3314559";
            string szAccountID = GetAccountString("TFX");
            int nForceQuery = TFXCheckForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.FutOpt_QueryOI(szAccountID, m_nTradeDate, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private int GetTFXBS()
        {
            int nBS = 2;    // 買賣別 (1: 買進/ 2: 賣出)
            if (cbTFX_BS.SelectedIndex == 0 || cbTFX_BS.SelectedIndex == 1)
            {
                nBS = cbTFX_BS.SelectedIndex + 1;
            }
            return nBS;
        }

        private int GetTFXType()
        {
            int nTT = 0;    // 期權商品類型 (0:期貨, 1:選擇權)
            if (cbTFXType.SelectedIndex == 0 || cbTFXType.SelectedIndex == 1)
            {
                nTT = cbTFXType.SelectedIndex;
            }
            return nTT;
        }
        #endregion

        #region HK
        private void btnHKNewOrder_Click(object sender, EventArgs e)
        {
            //string szAccountID = "20601-0101093";
            string szAccountID = GetAccountString("HK");
            int nTT = 0;
            int nOT = 0;
            int nBS = 1;    // 1: 買進/ 2: 賣出
            string szStockID = txtHKStockID.Text;
            if (!IsNumber(txtHKQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtHKQty.Text);
            int nPT = 0;
            string szPrice = txtHKPrice.Text;

            string strResult = m_tradeApp.HK_NewOrder(szAccountID, m_nTradeDate, nTT, nOT, nBS, szStockID, nQty, nPT, szPrice);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnHKModifyOrder_Click(object sender, EventArgs e)
        {
            string szAccountID = GetAccountString("HK");
            int nTT = 0;
            int nOT = 0;
            string szOID = txtHKOID.Text;
            int nBS = 1;    // 1: 買進/ 2: 賣出
            if (!IsNumber(txtHKQty.Text))
            {
                MessageBox.Show("請輸入數量");
                return;
            }
            int nQty = Convert.ToInt32(txtHKQty.Text);

            if (!IsNumber(txtHKAfterQty.Text))
            {
                MessageBox.Show("請輸入數量 (AfterQty)");
                return;
            }
            int nAfterQty = Convert.ToInt32(txtHKAfterQty.Text);
            int nBeforeQty = nAfterQty + nQty;

            int nPreOrder = 0;

            string strResult = m_tradeApp.HK_ModifyOrder(szAccountID, m_nTradeDate, nTT, nOT,
                szOID, txtHKStockID.Text, nBS, nBeforeQty, nAfterQty, nPreOrder,"","");

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnHKQryOrder_Click(object sender, EventArgs e)
        {
            string szAccountID = GetAccountString("HK");
            int nForceQuery = checkForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.HK_QueryOrder(szAccountID, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnHKQryMatch_Click(object sender, EventArgs e)
        {
            string szAccountID = GetAccountString("HK");
            int nForceQuery = checkForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.HK_QueryMatch(szAccountID, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnHKQryPosition_Click(object sender, EventArgs e)
        {
            string szAccountID = GetAccountString("HK");
            int nForceQuery = checkForceQuery.Checked ? 1 : 0;

            string strResult = m_tradeApp.HK_QueryPosition(szAccountID, m_nTradeDate, nForceQuery);

            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }
        #endregion

        #region Util

        public static bool IsNumber(string strNumber)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^\d+(\.)?\d*$");
            return r.IsMatch(strNumber);
        }

        public static string FormatResult(string strInput)
        { 
            return strInput.Replace("><", ">\n<");
        }

        #endregion

        private void btnMixQuery_Click(object sender, EventArgs e)
        {
            string szAccountID = GetAccountString("ALL");
            if (txtAPI.Text.Length <= 0)
            {
                MessageBox.Show("輸入 API");
                return;
            }
            string strResult = m_tradeApp.MIX_QueryData(szAccountID, txtAPI.Text, txtParam.Text);
            if (strResult != null && strResult.Length > 0)
                MessageBox.Show(strResult);
        }

        private void btnGetAID_Click(object sender, EventArgs e)
        {
            if (txtUID.Text.Length <= 0)
            {
                MessageBox.Show("請輸入身份證");
                return;
            }

            string strResult;
            try
            {
                strResult = m_tradeApp.GetAIDByUID(txtUID.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("查詢失敗");
                return;
            }

            if(strResult.Length >= 2)
            {
                if(strResult[0] == '|')
                {
                    strResult.Remove(0, 1);
                }
                if(strResult[strResult.Length - 1] == '|')
                {
                    strResult.Remove(strResult.Length - 1, 1);
                }
                string[] arAIDs = strResult.Split('|');
                if (arAIDs.Length > 0)
                {
                    cbAID.Items.Clear();
                    cbAID.Text = "";
                    foreach (string strAID in arAIDs)
                    {
                        string[] arAID = strAID.Split(',');
                        if (arAID.Length == 2)
                        {
                            if (cbAID.Text.Length == 0)
                            {
                                cbAID.Text = arAID[1];
                            }
                            cbAID.Items.Add(arAID[1]);
                        }
                    }
                }
            }
            
        }

        private void cbSTK_BS_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void txtQMatch_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtOID_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtOrderNo_TextChanged(object sender, EventArgs e)
        {

        }

        private void STKCheckForceQuery_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void txtRule_TextChanged(object sender, EventArgs e)
        {

        }

        private void StockGB_Enter(object sender, EventArgs e)
        {

        }

        private void label26_Click(object sender, EventArgs e)
        {

        }

        private void cbSTK_PT_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void txtConnStatus_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
