//2023.5.25 : 若要給版, 記得將阿嘿不達的CODE 移除("API",SkipCertCheck, NotiftyTtest....等等) 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Intelligence;
using Smart; 
using Package; 

namespace TradeComExample {
    
    public partial class Form1 : Form {
        private TaiFexCom tfcom;
        private UTF8Encoding encoding = new System.Text.UTF8Encoding();
       
        public Form1() {
            InitializeComponent();
            //先Create , 尚未正式連線,  IP 在正式連線時再輸入即可 ; 
            tfcom = new TaiFexCom("itrade.kgi.com.tw", 8000, "API",Language.Chinese  );
            
            this.Text = "TradeCom 範例程式 [ Version : " + tfcom.version + " ]";
            tfcom.OnRcvMessage += OnRcvMessage;          //資料接收事件
            tfcom.OnGetStatus += OnGetStatus;               //狀態通知事件
            
            tfcom.OnRcvServerTime += OnRcvServerTime;   //接收主機時間
            tfcom.OnRecoverStatus += OnRecoverStatus;   //回補狀態通知
            tabControl1.SelectedIndex = 0;
            tcResult.SelectedIndex = 0;
            InitDGVHeader();
          }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            tfcom.Logout();
            tfcom.Dispose();
        }
      
        private void SetLoginInfo()
        {
            tfcom.ServerHost = cbHost.Text;
            ushort.TryParse(cbPort.Text, out tfcom.ServerPort);
            //*********Auto Reconnect Push2 *************
            if (cbConn2Push.Checked)
            {
                tfcom.AutoRedirectPushLogin = true;
                tfcom.ServerHost2 = cbHost2.Text;
                ushort.TryParse(cbPort2.Text, out tfcom.ServerPort2);
                tfcom.LoginTimeout = 8000;
                
            }
            //************************
            tfcom.AutoRetriveProductInfo = cbProductBase.Checked;  //是否載入商品檔
            tfcom.AutoSubReport = cbSubReport.Checked;   //是否回補回報&註冊即時回報(國內)
            tfcom.AutoSubReportForeign = cbSubReportForeign.Checked;   //是否回補回報&註冊即時回報(國外)
            //2015.7.9 將即時 & 回補 回報分離; 未設定時則 AutoRecoverReport=AutoSubRepor ; 
            tfcom.AutoRecoverReport = cbRecover.Checked;
            tfcom.AutoRecoverReportForeign = cbRecoverF.Checked;
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            SetLoginInfo();
            tfcom.ShowLogin();       //顯示登入視窗


            while (tfcom.ConnectionStatus() != CONNECTION_STATUS.CS_CONNECTREADY)
                Thread.Sleep(100); 
        }
        private void btnLoginDirect_Click(object sender, EventArgs e)
        {
            SetLoginInfo();
            //不使用 TradeCom 提供之LOGIN FORM ; 直接代入登入資訊 ; 
            tfcom.LoginDirect(tfcom.ServerHost, tfcom.ServerPort, tbLogDirectInfo.Text);
        }
        private void btnLogout_Click(object sender, EventArgs e)
        {
            tfcom.Logout();
        }



        #region TaiFexCom API 事件

        private void OnGetStatus(object sender, COM_STATUS staus, byte[] msg) {
            if (this.InvokeRequired) {
                Smart.OnGetStatus_EventHandler d = new Smart.OnGetStatus_EventHandler(OnGetStatus);
                this.Invoke(d, new object[] { sender, staus, msg });
                return;
            }
            OnGetStatusUpdateUI(sender, staus, msg);
        }

        private void OnRcvMessage(object sender, PackageBase package) {
            if (this.InvokeRequired) {
                OnRcvMessage_EventHandler d = new OnRcvMessage_EventHandler(OnRcvMessage);
                this.Invoke(d, new object[] { sender, package });
                return;
            }
            switch ((DT)package.DT)
            {

                #region Login 
                case DT.LOGIN:
                    P001503 p1503 = (P001503)package;
                    if (p1503.Code != 0)
                        AddInfo("登入失敗 CODE = " + p1503.Code + " " + tfcom.GetMessageMap(p1503.Code));
                    else {
                        AddInfo("登入成功 ");
                        AddInfo(p1503.ToLog());
                    }
                    
                    break;
                #endregion 
                case DT.PreviousLogin:
                    P001507 p1507 = (P001507)package;
                    AddInfo("前次登入:" + p1507.ToLog()); 
                    break;
                case DT.SUBACCT_CHG_PWD:
                    P001753 p1753 = (P001753)package ; 
                    AddInfo(p1753.ToLog()); 
                    break ; 
                #region 公告
                case DT.NOTICE_RPT : 
                    P001701  p1701 = (P001701)package;
                    AddInfo(p1701.ToLog());
                    break ;    //公告(被動查詢) 
                case DT.NOTICE  :   //公告(主動)
                    P001702  p1702 = (P001702)package;
                    AddInfo(p1702.ToLog());
                    break; 
                #endregion 

                #region 國內下單回報
                case DT.FUT_ORDER_ACK:   //下單第二回覆
                    PT02002 p2002 = (PT02002)package;
                    AddInfo(p2002.ToLog() );
                    break;
                case DT.FUT_ORDER_RPT: //委託回報
                    PT02010 p2010 = (PT02010)package;
                    AddInfo(p2010.ToLog());
                    string[] row2010 = { p2010.OrderFunc.ToString(), p2010.FrontOffice.ToString(), p2010.BrokerId, p2010.Account, p2010.OrderNo, p2010.TradeDate, p2010.ReportTime, p2010.ClientOrderTime, p2010.WebID, p2010.CNT, p2010.TimeInForce.ToString(), p2010.Symbol, p2010.Side.ToString(), p2010.PriceMark.ToString(), p2010.Price, p2010.PositionEffect.ToString(), p2010.BeforeQty, p2010.AfterQty, p2010.Code, p2010.ErrMsg, p2010.Trader,p2010.Market ,p2010.ReportTime2 };
                    dgv2010.Rows.Add(row2010);
                    break;
                case DT.FUT_DEAL_RPT:   //成交回報
                    PT02011 p2011 = (PT02011)package;
                    AddInfo(p2011.ToLog());
                    AddInfo("RCV 2011 [" + p2011.OrderNo + "]");
                    string[] row2011 = { p2011.OrderFunc.ToString(), p2011.FrontOffice.ToString(), p2011.BrokerId, p2011.Account, p2011.OrderNo, p2011.TradeDate, p2011.ReportTime, p2011.WebID, p2011.CNT, p2011.Symbol, p2011.Side.ToString(), p2011.Market.ToString(), p2011.DealPrice, p2011.DealQty, p2011.CumQty, p2011.LeaveQty, p2011.MarketNo, p2011.Symbol1, p2011.DealPrice1, p2011.Qty1, p2011.BS1.ToString(), p2011.Symbol2, p2011.DealPrice2, p2011.Qty2, p2011.BS2.ToString(), p2011.Trader,p2011.ReportTime2 };
                    dgv2011.Rows.Add(row2011); 
                    break;
                #endregion 

                #region 國外下單回報
                case DT.FFUT_ORDER_ACK:   //下單第二回覆
                    PT03302 p3302 = (PT03302)package;
                    AddInfo(p3302.ToLog());
                    break;
                case DT.FFUT_ORDER_RPT: //委託回報
                    PT03310 p3310 = (PT03310)package;
                    AddInfo(string.Format("Receive {0} ErrCode:{1} CNT:{2} ASorderNo:{3}" , "3310",p3310.ErrCode ,p3310.CNT,p3310.ASorderNo ));
                    string[] row3310 = { p3310.OrderFunc.ToString(), p3310.Exchange, p3310.FCM, p3310.FFUT_ACCOUNT, p3310.ORDNO, p3310.ASorderNo, p3310.BrokerId, p3310.Account, p3310.AE, p3310.TradeDate, p3310.ReportTime, p3310.WEBID, p3310.SOURCE, p3310.OrgCnt, p3310.CNT, p3310.Symbol, p3310.ComYM, p3310.StrikePrice, p3310.CP.ToString(), p3310.BS.ToString(), p3310.TimeInForce.ToString(), p3310.PriceFlag.ToString(), p3310.PositionEffect.ToString(), p3310.DayTrade.ToString(), p3310.Price, p3310.StopPrice, p3310.BeforeQty, p3310.AfterQty, p3310.KeyIn, p3310.ErrCode, p3310.ErrMsg};
                    dgv3310.Rows.Add(row3310);
                    break;
                case DT.FFUT_DEAL_RPT:   //成交回報
                    PT03311 p3311 = (PT03311)package;
                    AddInfo("RCV 3311 [" + p3311.CNT  + "]");
                    string[] row3311 = { p3311.OrderFunc.ToString(), p3311.Exchange, p3311.FCM, p3311.FFUT_ACCOUNT, p3311.ORDNO, p3311.ASorderNo, p3311.BrokerId, p3311.Account, p3311.AE, p3311.TradeDate, p3311.ReportTime, p3311.WEBID, p3311.SOURCE, p3311.CNT, p3311.Symbol, p3311.ComYM, p3311.StrikePrice, p3311.CP.ToString(), p3311.BS.ToString(), p3311.TimeInForce.ToString(), p3311.PriceFlag.ToString(), p3311.PositionEffect.ToString(), p3311.DayTrade.ToString(), p3311.DealPrice, p3311.AvgPrice, p3311.DealQty, p3311.PATSNo, p3311.LeavesQty, p3311.CumQty, p3311.KeyIn};
                    dgv3311.Rows.Add(row3311); 
                    break;

                case DT.FFUT_ORDER_RPT2: //委託回報-複式單
                    PT03314 p3314 = (PT03314)package;
                    AddInfo(string.Format("Receive {0} ErrCode:{1} CNT:{2} ASorderNo:{3}", "3314", p3314.ErrCode, p3314.CNT, p3314.ASorderNo));
                    string[] row3314 = { p3314.OrderFunc.ToString(), p3314.Exchange, p3314.FCM, p3314.FFUT_ACCOUNT, p3314.ORDNO, p3314.ASorderNo, p3314.BrokerId, p3314.Account, p3314.AE, p3314.TradeDate, p3314.ReportTime, p3314.WEBID, p3314.SOURCE, p3314.OrgCnt, p3314.CNT, p3314.Symbol, p3314.ComYM, p3314.StrikePrice, p3314.CP.ToString(), p3314.BS.ToString(), p3314.Symbol2,p3314.ComYM2,p3314.StrikePrice2,p3314.CP2.ToString(),p3314.BS2.ToString(), p3314.TimeInForce.ToString(), p3314.PriceFlag.ToString(), p3314.PositionEffect.ToString(), p3314.DayTrade.ToString(), p3314.Price, p3314.StopPrice, p3314.BeforeQty, p3314.AfterQty,p3314.OrgKeyin, p3314.KeyIn, p3314.ErrCode, p3314.ErrMsg};
                    dgv3314.Rows.Add(row3314);
                    break;
                case DT.FFUT_DEAL_RPT2:   //成交回報-複式單
                    PT03315 p3315 = (PT03315)package;
                    AddInfo("RCV 3315 [" + p3315.CNT + "]");
                    string[] row3315 = { p3315.OrderFunc.ToString(), p3315.Exchange, p3315.FCM, p3315.FFUT_ACCOUNT, p3315.ORDNO, p3315.ASorderNo, p3315.BrokerId, p3315.Account, p3315.AE, p3315.TradeDate, p3315.ReportTime, p3315.WEBID, p3315.SOURCE, p3315.CNT, p3315.Symbol, p3315.ComYM, p3315.StrikePrice, p3315.CP.ToString(), p3315.BS.ToString(), p3315.TimeInForce.ToString(), p3315.PriceFlag.ToString(), p3315.PositionEffect.ToString(), p3315.DayTrade.ToString(), p3315.DealPrice, p3315.AvgPrice, p3315.DealQty, p3315.PATSNo, p3315.LeavesQty, p3315.CumQty, p3315.KeyIn};
                    dgv3315.Rows.Add(row3315);
                    break;
                
                #endregion 

                #region 帳務查詢
                case DT.FINANCIAL_COVER_TRADER : //1614 
                    P001614 p1614 = (P001614)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}" , "1614",p1614.Code ,p1614.Rows ));
                    dgv1614.Rows.Clear(); 
                    if (p1614.Rows > 0) {
                        foreach (P001614_2 p1614b in p1614.p001614_2) {
                            string[] row1614 ={ p1614b.BrokerId, p1614b.Account, p1614b.Group, p1614b.Trader, p1614b.Exchange, p1614b.ComID, p1614b.ComYM, p1614b.StrikePrice, p1614b.CP, p1614b.CURRENCY, p1614b.PRTLOS, p1614b.CTAXAMT, p1614b.ORIGNFEE, p1614b.OSPRTLOS, p1614b.Qty, p1614b.OSPRTLOS_TWD };
                            dgv1614.Rows.Add(row1614);
                        }
                    }
                    break;
                case DT.INVENTORY_TRADER: //1616
                    P001616 p1616 = (P001616)package;
                    dgv1616.Rows.Clear() ;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1616", p1616.Code, p1616.Rows));
                    if (p1616.Rows > 0) {
                        foreach (P001616_2 p1616b in p1616.p001616_2) {
                            string[] row1616 = { p1616b.BrokerId, p1616b.Account, p1616b.Group, p1616b.Trader, p1616b.Exchange, p1616b.ComType, p1616b.ComID, p1616b.ComYM, p1616b.StrikePrice, p1616b.CP, p1616b.BS, p1616b.DeliveryDate, p1616b.Currency, p1616b.OTQty, p1616b.TrdPrice, p1616b.MPrice, p1616b.PRTLOS, p1616b.DealPrice };
                            dgv1616.Rows.Add(row1616);
                        }
                    }
                    break;
                case DT.INVENTORY_DETAIL_TRADER:  //1618
                    P001618 p1618 = (P001618)package;
                    dgv1618.Rows.Clear() ;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1618", p1618.Code, p1618.Rows));
                    if (p1618.Rows > 0) {
                        foreach (P001618_2 p1618b in p1618.p001618_2) {
                            string[] row1618 = { p1618b.BrokerId, p1618b.Account, p1618b.Group, p1618b.Trader, p1618b.Exchange, p1618b.SeqNo, p1618b.FcmActNo, p1618b.TradeType, p1618b.FCM, p1618b.DeliveryDate, p1618b.CloseDate, p1618b.WEB, p1618b.Cnt, p1618b.OrdNo, p1618b.MarketNo, p1618b.sNo, p1618b.TradeDate, p1618b.ComID, p1618b.BS.ToString(), p1618b.ComType.ToString(), p1618b.CP.ToString(), p1618b.StrikePrice, p1618b.ComYM, p1618b.Qty, p1618b.TrdPrice, p1618b.MPrice, p1618b.PRTLOS, p1618b.InitialMargin, p1618b.MTMargin, p1618b.Currency, p1618b.DealPrice, p1618b.MixQty, p1618b.DayTrade.ToString(), p1618b.SPREAD.ToString(), p1618b.spKey.ToString(), p1618b.OrdNo2, p1618b.MarketNo2, p1618b.sNo2, p1618b.TradeDate2, p1618b.ComID2, p1618b.BS2.ToString(), p1618b.ComType2.ToString(), p1618b.CP2.ToString(), p1618b.StrikePrice2, p1618b.ComYM2, p1618b.Qty2, p1618b.TrdPrice2, p1618b.MPrice2, p1618b.PRTLOS2, p1618b.InitialMargin2, p1618b.MTMargin2, p1618b.Currency2, p1618b.DealPrice2, p1618b.MixQty2, p1618b.DayTrade2.ToString() };
                            dgv1618.Rows.Add(row1618);
                        }
                    }
                    break ; 
                case DT.FINANCIAL_COVER_TRADER_Detail:  //1624 
                    P001624 p1624 = (P001624)package;
                    dgv1624.Rows.Clear() ;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1624", p1624.Code, p1624.Rows));
             
                    if (p1624.Rows > 0) {
                        foreach(P001624_2 p1624b in p1624.p001624_2 ){
                            string[] row1624 = {p1624b.BrokerId,p1624b.Account,p1624b.Group,p1624b.Trader,p1624b.Exchange,p1624b.OccDT,p1624b.TrdDT1,p1624b.OrdNo1,p1624b.FirmOrd1,p1624b.OffsetSpliteSeqNo,p1624b.TrdDT2,p1624b.OrdNo2,p1624b.FirmOrd2,p1624b.OffsetSpliteSeqNo2,p1624b.OffsetCode.ToString(),p1624b.offset.ToString(),p1624b.BS.ToString(),p1624b.ComID,p1624b.ComYM,p1624b.StrikePrice,p1624b.CP.ToString(),p1624b.ComID2,p1624b.Qty1,p1624b.Qty2,p1624b.TrdPrice1,p1624b.TrdPrice2,p1624b.PRTLOS,p1624b.AENO,p1624b.Currency,p1624b.CTAXAMT,p1624b.ORIGNFEE,p1624b.Premium1,p1624b.Premium2,p1624b.InNo1,p1624b.InNo2,p1624b.Cnt1,p1624b.Cnt2,p1624b.OSRTLOS };
                            dgv1624.Rows.Add(row1624);                    
                        }
                    }
                    break ; 
                  
                  case DT.FINANCIAL_TRADERN : //1626 
                    P001626 p1626 = (P001626)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1626", p1626.Code, p1626.Count));
                    dgv1626.Rows.Clear() ; 
                    if (p1626.Count > 0) {
                        foreach (P001626_2 p1626b in p1626.p001626_2){
                            //,p1626b.WithdrawMnt 
                            string[] row1626 = { p1626b.BrokerId, p1626b.Account, p1626b.Group, p1626b.Trader, p1626b.Currency, p1626b.LCTDAB, p1626b.ORIGNFEE, p1626b.TAXAMT, p1626b.CTAXAMT, p1626b.DWAMT, p1626b.OSPRTLOS, p1626b.PRTLOS, p1626b.BMKTVAL, p1626b.SMKTVAL, p1626b.OPREMIUM, p1626b.TPREMIUM, p1626b.EQUITY, p1626b.IAMT, p1626b.MAMT, p1626b.EXCESS, p1626b.ORDEXCESS, p1626b.ORDAMT, p1626b.ExProfit, p1626b.Premium, p1626b.PTime, p1626b.FloatProfit, p1626b.LASSPRTLOS, p1626b.CLOSEAMT, p1626b.ORDIAMT, p1626b.ORDMAMT, p1626b.DayTradeAMT, p1626b.ReductionAMT, p1626b.CreditAMT, p1626b.balance, p1626b.IPremium, p1626b.OPremium, p1626b.Securities, p1626b.SecuritiesOffset, p1626b.OffsetAMT, p1626b.Offset, p1626b.FULLMTRISK, p1626b.FULLRISK, p1626b.MarginCall, p1626b.SellVerticalSpread, p1626b.StrikePrice, p1626b.ActMarketValue, p1626b.TPRTLOS, p1626b.MarginCall1, p1626b.AddMargin, p1626b.ORDAMTNOCN,p1626b.WithdrawMnt };
                            dgv1626.Rows.Add(row1626);                     
                        }
                    }
                    break;
                
                case DT.FINANCIAL_CURRENCY : //1628 
                    P001628 p1628 = (P001628)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Msg:{2}", "1628", p1628.Code, p1628.ErrorMsg));
                
                    break;
                case DT.FINANCIAL_STRIKE :   //2017.2.4 1643  無效履約查詢
                    P001643 p1643 = (P001643)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1643", p1643.Code, p1643.Rows ));
                    dgv1643.Rows.Clear() ;
                    if (p1643.Rows > 0)
                    {
                        foreach (P001643_2 p1643b in p1643.Detail)
                        {
                            string[] row1643 = { p1643b.BrokerId, p1643b.Account, p1643b.Group, p1643b.Trader,p1643b.DueDate,p1643b.TrdDate,p1643b.OrdNo,p1643b.FirmOrd,p1643b.SeqNo,p1643b.Exchange,p1643b.ComID,p1643b.ComYM,p1643b.StrikePrice,p1643b.CP.ToString(),p1643b.BS.ToString(),p1643b.Qty,p1643b.TaxCurr,p1643b.TaxAmt,p1643b.FeeCurr,p1643b.FeeAmt,p1643b.TrdCurr,p1643b.Premium,p1643b.TrdPre } ; 
                            dgv1643.Rows.Add(row1643);
                        }
                    }        
                    
                    break ; 
                case DT.FINANCIAL_COVERDH :     //2017.2.14  1645 ; 平倉明細歷史查詢
                    P001645 p1645 = (P001645)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1645", p1645.Code, p1645.Rows));
                
                    dgv1645.Rows.Clear();
                    if (p1645.Rows > 0) {
                        foreach(P001645_2 p1645b in p1645.Detail  ){
                            //string[] header1645 = { "市場別", "分公司", "帳號"          , "組別",                       "交易員",                                  "交易所"              , "平倉日期",     "平倉成交日期", "平倉委託編號", "平倉成交序號",         "平倉拆單序號", "被平成交日期",     "被平委託編號",   "被平成交序號",     "被平拆單序號",          "指定平倉碼",                               "互抵",                                       "BS",                        "商品代號", "商品年月", "履約價 ", "CP", "被平商品代號", "平倉口數", "被平口數", "平倉成交價", "被平成交價", "平倉損益", "業務員代號", "幣別", "交易稅", "手續費", "平倉權利金", "被平權利金", "平倉場內編號", "被平場內編號", "平倉電子單號", "被平電子單號" };
                            string[] row1645 = { p1645b.Market, p1645b.BrokerId, p1645b.Account, p1645b.Group, p1645b.Trader, p1645b.Exchange, p1645b.OccDT, p1645b.TrdDT1, p1645b.OrdNo1, p1645b.FirmOrd1, p1645b.OffsetSpliteSeqNo, p1645b.TrdDT2, p1645b.OrdNo2, p1645b.FirmOrd2, p1645b.OffsetSpliteSeqNo2, p1645b.OffsetCode.ToString(), p1645b.offset.ToString(), p1645b.BS.ToString(), p1645b.ComID, p1645b.ComYM, p1645b.StrikePrice, p1645b.CP.ToString(), p1645b.ComID2, p1645b.Qty1, p1645b.Qty2, p1645b.TrdPrice1, p1645b.TrdPrice2, p1645b.PRTLOS, p1645b.AENO, p1645b.Currency, p1645b.CTAXAMT, p1645b.ORIGNFEE, p1645b.Premium1, p1645b.Premium2, p1645b.InNo1, p1645b.InNo2, p1645b.Cnt1, p1645b.Cnt2 ,p1645b.CurrencyRate};
                            dgv1645.Rows.Add(row1645);                    
                        }
                    }
                    break;

                case DT.FINANCIAL_DEALH:   //2023.3.20 : 歷史成交查詢
                    P001655 p1655 = (P001655)package;
                    AddInfo(string.Format("Receive {0} Code:{1}{2} Rows:{3}", "1655", p1655.Code,p1655.ErrMessage,p1655.Rows));
                
                    dgv1655.Rows.Clear();
                    if (p1655.Rows > 0) {
                        foreach(P001655_2 p1655b in p1655.Detail  ){
                            
                            string[] row1655 = {p1655b.BrokerId,p1655b.Account,p1655b.Group,p1655b.Trader,p1655b.Exchange,p1655b.Symbol,p1655b.ComYM,p1655b.StrikePrice,p1655b.CP.ToString(),p1655b.Market.ToString(),p1655b.Offset.ToString(),p1655b.BS.ToString(),p1655b.Price,p1655b.AvgPrice,p1655b.OrdQty,p1655b.DealQty,p1655b.TradeDate,p1655b.DealTime,p1655b.OrdNo,p1655b.Source.ToString(),p1655b.OrdCNT};
                            dgv1655.Rows.Add(row1655);                    
                        }
                    }
                    break; 

                case DT.FINANCIAL_RECIPROCATE:  //大小台互抵
                         P001647  p1647 = (P001647)package;
                         string msg = p1647.BrokerId + p1647.Account;
                         if (p1647.Status == "0")
                             AddInfo(msg + "大小台互抵成功: 大台 " + p1647.Qty1 + " ,小台 " + p1647.Qty2);
                         else
                             AddInfo(msg + " 大小台互抵失敗"); 
                    break; 
          
                case DT.FINANCIAL_SERVICECHARGE : //1631  手續費; 
                    P001631 p1631 = (P001631)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1631", p1631.Code, p1631.Count));
                    dgv1631.Rows.Clear();
                    if (p1631.Count > 0) {
                        foreach (P001631_2 p1631b in p1631.p001631_2 ) {
                            string[] row1631 = {p1631b.BrokerId,p1631b.Account,p1631b.Group,p1631b.Trader,p1631b.Kind,p1631b.Class,p1631b.Qty,p1631b.Method.ToString(),p1631b.Rule.ToString(),p1631b.Amt,p1631b.Rate,p1631b.Currency }; 
                            dgv1631.Rows.Add(row1631);
                        }
                    }
                    break; 
                case DT.FINANCIAL_APPLYWITHDRAW_PWD  : //1633 出金申請; 

                    P001651 p1633 = (P001651)package;
                    AddInfo(string.Format("Receive {0} Code:{1}", "1651", p1633.Code));
                    string[] row1633 = { p1633.Webid,p1633.Seqno , p1633.ApplyNo,p1633.UpdateTime,p1633.ApplyDate,p1633.ApplyTime,p1633.AMT,p1633.Code,p1633.ErrorMsg };
                    dgv1633.Rows.Add(row1633);
                    
                    break; 
                case DT.FINANCIAL_WITHDRAW  : //1635 ; 
                      P001635 p1635 = (P001635)package;
                      AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1635", p1635.Code, p1635.Count));
                   dgv1635.Rows.Clear();
                    if (p1635.Count > 0) {
                        foreach (P001635_2 p1635b in p1635.p001635_2 ) {
                            string[] row1635 = {p1635b.Webid , p1635b.Seqno,p1635b.Market,p1635b.Type,p1635b.UpdateDate,p1635b.WithdrawNo , p1635b.BankNo,p1635b.BankAccount,p1635b.Currency,p1635b.Amt,p1635b.NTAmt , p1635b.Status}; 
                            dgv1635.Rows.Add(row1635);
                        }
                    } 
                    break;
                case DT.FINANCIAL_RT_WITHDRAW: //1657 : 出金查詢
                    P001657 p1657 = (P001657)package;
                    AddInfo(string.Format("Receive {0} Code:{1} Rows:{2}", "1657", p1657.Code, p1657.RowsCount));
                    AddInfo(p1657.ToLog()); 
                    break;
                case DT.FINANCIAL_FLEX: //1659 : 2023.10. 客製化商品權益數
                    P001659 p1659 = (P001659)package;
                    AddInfo(string.Format("夜盤商品權益數<1659> Code:{0} Rows:{1}", p1659.Code, p1659.Count));
                    dgv1659.Rows.Clear();
                    if (p1659.Count > 0)
                    {
                        foreach (P001659_2 p1659b in p1659.Detail)
                        {
                            string[] row1659 = { p1659b.MType,p1659b.BrokerId, p1659b.Account, p1659b.Group, p1659b.Trader, p1659b.Currency, p1659b.LCTDAB, p1659b.ORIGNFEE, p1659b.TAXAMT, p1659b.CTAXAMT, p1659b.DWAMT, p1659b.OSPRTLOS, p1659b.PRTLOS, p1659b.BMKTVAL, p1659b.SMKTVAL, p1659b.OPREMIUM, p1659b.TPREMIUM, p1659b.EQUITY, p1659b.IAMT, p1659b.MAMT, p1659b.EXCESS, p1659b.MoneyCall, p1659b.ExProfit, p1659b.Premium, p1659b.ORDIAMT, p1659b.ORDMAMT, p1659b.ReductionAMT, p1659b.ReductionMAMT, p1659b.FULLRISK, p1659b.AddMargin, p1659b.SUTRATE, p1659b.PremiumVal, p1659b.RiskRate, p1659b.FloatProfit, p1659b.ActMarketValue, p1659b.MarginCall, p1659b.Balance, p1659b.SecuritiesOffset, p1659b.BookAmt };
                            dgv1659.Rows.Add(row1659);
                        }
                    }
                    break;

                #endregion 

                #region 組拆功能 2024.10
                case DT.FINANCIAL_NETCOVERFU: // 1649.網路批次互抵申請
                    P001649 p1649 = (P001649)package;
                    AddInfo("網路批次互抵申請:" + p1649.ToLog()); 
                    break;
                case DT.FINANCIAL_NETCOVER : //1665 網路指定平倉申請
                    P001665 p1665 = (P001665)package;
                    AddInfo("網路批次互抵申請:" + p1665.ToLog()); 
                    break;
                case DT.FINANCIAL_NETOPTAS : //1667:網路拆組申請
                     P001667 p1667 = (P001667)package;
                     AddInfo("網路拆組申請:" + p1667.ToLog()); 
                    break;
                case DT.FINANCIAL_NETOPTIM : //1669 網路部分拆平組申請
                    P001669 p1669 = (P001669)package;
                     AddInfo("網路拆組申請:" + p1669.ToLog()); 
                    break; 
                    
                #endregion 

            }
        }


        
        private void OnRcvServerTime(Object sender, DateTime serverTime, int ConnQuality) {
            if (this.InvokeRequired) {
                OnRcvServerTime_EventHandler d = new OnRcvServerTime_EventHandler(OnRcvServerTime);
                this.Invoke(d, new object[] { sender, serverTime, ConnQuality });
                return;
            }
            if (ConnQuality > 100)
                pbConnQuality.Value = 0;
            else
                pbConnQuality.Value = 100 - ConnQuality;
            labelServerTime.Text = String.Format("{0:hh:mm:ss.fff}", serverTime);
            labelConnQuality.Text = "[" + ConnQuality + "]";
            
        }

        private void OnRecoverStatus(object sender, string Topic, RECOVER_STATUS status, uint RecoverCount) {
            if (this.InvokeRequired) {
                OnRecover_EvenHandler d = new OnRecover_EvenHandler(OnRecoverStatus);
                this.Invoke(d, new object[] { sender, Topic, status, RecoverCount });
                return;
            }

            TaiFexCom com = (TaiFexCom)sender;
            switch (status) {
                case RECOVER_STATUS.RS_DONE:        //回補資料結束
                    if (RecoverCount == 0)
                        AddInfo(String.Format("結束回補 Topic:[{0}]", Topic));
                    else AddInfo(String.Format("結束回補 Topic:[{0} 筆數:{1}]", Topic, RecoverCount));
                    break;
                case RECOVER_STATUS.RS_BEGIN:       //開始回補資料
                    AddInfo(String.Format("開始回補 Topic:[{0}]", Topic));
                    break;
            }
        }


        #endregion ;

        #region UI 呈現
        private void OnGetStatusUpdateUI(object sender, COM_STATUS staus, byte[] msg) {
            TaiFexCom com = (TaiFexCom)sender;
            string smsg = null;
            switch (staus) {
                case COM_STATUS.LOGIN_READY:          //登入成功
                    AddInfo("登入成功:" + com.Accounts);
                    break;
                case COM_STATUS.LOGIN_FAIL:             //登入失敗
                    AddInfo(String.Format("登入失敗:[{0}]", encoding.GetString(msg)));
                    break;
                case COM_STATUS.LOGIN_UNKNOW:       //登入狀態不明
                    AddInfo(String.Format("登入狀態不明:[{0}]", encoding.GetString(msg)));
                    break;
                case COM_STATUS.NOVALIDCERT:  
                    AddInfo(string.Format("電腦中查無您有效憑證[{0}]，請至憑證中心申請/匯入憑證後，再重新登入!!", encoding.GetString(msg)));
                    break; 
                case COM_STATUS.CONNECT_READY:      //連線成功
                    smsg = "伺服器" + tfcom.ServerHost + ":" + tfcom.ServerPort + Environment.NewLine +
                              "伺服器回應: [" + encoding.GetString(msg) + "]" + Environment.NewLine +
                              "本身為" + ((tfcom.isInternal) ? "內" : "外") + "部 IP:" + tfcom.MyIP;
                    AddInfo(smsg);
                    break;
                case COM_STATUS.CONNECT_FAIL:       //連線失敗
                    smsg = encoding.GetString(msg);
                    AddInfo("連線失敗:" + smsg + " " + tfcom.ServerHost + ":" + tfcom.ServerPort);
                    break;
                case COM_STATUS.DISCONNECTED:       //斷線
                    smsg = encoding.GetString(msg);
                    AddInfo("斷線:" + smsg);
                    break;
                case COM_STATUS.SUBSCRIBE:
                    com.WriterLog("msg.Length=" + msg.Length);
                    smsg = encoding.GetString(msg);
                    com.WriterLog(String.Format("註冊:[{0}]", smsg));
                    AddInfo(String.Format("註冊:[{0}]", smsg));
                    break;
                case COM_STATUS.UNSUBSCRIBE:
                    smsg = encoding.GetString(msg);
                    AddInfo(String.Format("取消註冊:[{0}]", smsg));
                    break;
                case COM_STATUS.ACK_REQUESTID:          //下單或改單第一次回覆
                    long RequestId = BitConverter.ToInt64(msg, 0);
                    byte status = msg[8];
                    AddInfo("序號回覆: " + RequestId + " 狀態=" + ((status == 1) ? "收單" : "失敗"));
                    break;
                case COM_STATUS.QUEUE_WARNING :
                    smsg = encoding.GetString(msg);
                    AddInfo(smsg);
                    lbQueueWarn.Text = smsg; 
                    break; 
          
            }
        }
        private void AddInfo(string msg) {
            string[] row = { DateTime.Now.ToString("HH:mm:ss:fff"), msg };
            try {
                Info.Rows.Insert(0, row);
            }
            catch { }
        }
        private void InitDGVHeader() {
            string[] header2010 = { "委託型態", "FrontOffice", "分公司代號", "帳號", "委託書號", "交易日期", "回報時間", "委託日期時間", "主機別", "電子單號", "委託方式", "商品代碼", "買賣別", "市/限價", "委託價格", "新/平倉", "改量前數量", "改量後數量", "委託錯誤碼", "錯誤訊息", "子帳號(Trader)","商品別","時間2"};
            string[] header2011 = { "委託型態", "FrontOffice", "分公司代號", "帳號", "委託書號", "交易日期", "回報時間", "主機別", "電子單號", "商品代碼", "買賣別", "Market", "成交價格", "成交數量", "已成交總量", "剩餘成交量", "市場成交序號", "商品代號1", "成交價格1", "成交數量1", "買賣別1", "商品代號2", "成交價格2", "成交數量2", "買賣別2", "子帳號(Trader)","時間2" };
            string[] header3310 = { "委託型態", "交易所", "上手券商", "上手帳號", "上手委託書號", "AS400委託書號", "分公司代號", "帳號", "子帳帳號", "交易日期", "回報時間", "委託平台", "來源別", "原委託網路單號", "委託網路單號", "商品代碼", "商品年月", "履約價", "CP", "BS", "F/I/R", "市/限價", "新/平倉", "當日沖銷", "價格", "停損價", "改量前數量", "改量後數量", "交易員", "錯誤碼", "錯誤訊息"};
            string[] header3311 = { "委託型態", "交易所", "上手券商", "上手帳號", "上手委託書號", "AS400委託書號", "分公司代號", "帳號", "子帳帳號", "交易日期", "回報時間", "委託平台", "來源別", "委託網路單號", "商品代碼", "商品年月", "履約價", "CP", "BS", "F/I/R", "市/限價", "新/平倉", "當日沖銷", "成交價格", "成交均價", "成交口數", "成交序號", "剩餘有效口數", "總成交口數", "keyin"};
            string[] header1614 = { "分公司", "帳號", "組別", "交易員", "交易所", "商品代碼", "商品年月", "履約價", "CP", "幣別", "平倉損益", "交易稅", "手續費", "淨損益", "平倉口數", "平倉損益(TWD)" };
            string[] header1616 = { "分公司", "帳號", "組別", "交易員", "交易所", "期/權", "商品代碼", "商品年月", "履約價", "CP", "BS", "交割日期(外)", "幣別", "未平倉量", "結算價", "即時價", "未平倉損益", "成交均價" };
            string[] header1618 = { "分公司", "帳號", "組別", "交易員", "交易所", "場內編號(外)", "上手帳號(外)", "交易方式", "上手券商", "交割日期(外)", "結算日期(外)", "下單方式", "電子單號", "委託書號", "成交序號", "拆單序號", "成交日期", "商品代碼", "BS", "期/權", "CP", "履約價", "商品年月", "未平倉量", "結算價", "即時價", "未平倉損益", "原始保證金", "維持保證金", "幣別", "成交價", "混合口數一", "當日沖銷 ", "SPREAD", "複式組合單號", "委託書號2", "成交序號2", "拆單序號2", "成交日期2", "商品代碼2", "BS2", "期/權2", "CP2", "履約價2", "商品年月2", "未平倉量2", "結算價2", "即時價2", "未平倉損益2", "原始保證金2", "維持保證金2", "幣別2", "成交價2", "混合口數2", "當日沖銷2" };
            string[] header1624 = { "分公司", "帳號", "組別", "交易員", "交易所", "平倉日期", "平倉成交日期", "平倉委託編號", "平倉成交序號", "平倉拆單序號", "被平成交日期", "被平委託編號", "被平成交序號", "被平拆單序號", "指定平倉碼", "互抵", "BS", "商品代號", "商品年月", "履約價 ", "CP", "被平商品代號", "平倉口數", "被平口數", "平倉成交價", "被平成交價", "平倉損益", "業務員代號", "幣別", "交易稅", "手續費", "平倉權利金", "被平權利金", "平倉場內編號", "被平場內編號", "平倉電子單號", "被平電子單號", "淨損益" };
            //,"可出金金額" 
            string[] header1626 = { "分公司", "帳號", "組別", "交易員", "幣別", "前日餘額", "手續費", "匯率", "期交稅", "存提", "平倉損益", "未平倉損益", "未沖銷買方選擇權市值", "未沖銷賣方選擇權市值", "委託權利金", "權利金收入與支出", "權益數", "原始保證金", "維持保證金", "可用餘額", "可動用(出金)保證金", "委託保證金", "到期履約損益", "變動權利金", "洗價時間", "未沖銷期貨浮動損益", "昨日未沖銷期貨浮動損益", "到期結算保證金", "足額原始保證金", "足額維持保證金", "當沖原始保證金", "多空減收保證金", "當沖應補保證金", "本日餘額", "本日權利金收入", "本日權利金支出", "有價証券價值", "有價証券抵繳金額", "委託抵繳保證金", "剩餘可抵繳金額", "足額風險指標", "足額權益比例", "追繳金額", "賣方垂直價差市價", "履約價款", "權益總值", "本日期貨平倉損益淨額", "超額/追繳保證金", "加收保證金", "可動用(不含 CN$超額)" ,"可出金金額"};

            string[] header1631 = { "分公司", "帳號", "組別", "交易員", "特定費用分類", "費用分類", "口數", "計算方式", "定額/率", "金額", "定率比率", "幣別"};
            string[] header1633 = { "Webid", "網路序號", "出金批號", "後台異動時間", "申請日期", "申請時間", "可用餘額", "ErrorCode", "訊息" };
            string[] header1635 = { "Webid", "網路序號", "國內/外","存提類別C/D","異動日期","存提單號","存解款銀行","存解款帳號","幣別","原幣金額","台幣金額","已出磁片否"};


            string[] header3314 = { "委託型態", "交易所", "上手券商", "上手帳號", "上手委託書號", "AS400委託書號", "分公司代號", "帳號", "子帳帳號", "交易日期", "回報時間", "委託平台", "來源別", "原委託網路單號", "委託網路單號", "商品代碼", "商品年月", "履約價", "CP", "BS", "商品代碼2", "商品年月2", "履約價2", "CP2", "BS2", "F/I/R", "市/限價", "新/平倉", "當日沖銷", "價格", "停損價", "改量前數量", "改量後數量", "原交易員","交易員", "錯誤碼", "錯誤訊息" };
            string[] header3315 = { "委託型態", "交易所", "上手券商", "上手帳號", "上手委託書號", "AS400委託書號", "分公司代號", "帳號", "子帳帳號", "交易日期", "回報時間", "委託平台", "來源別", "委託網路單號", "商品代碼", "商品年月", "履約價", "CP", "BS", "F/I/R", "市/限價", "新/平倉", "當日沖銷", "成交價格", "成交均價", "成交口數", "成交序號", "剩餘有效口數", "總成交口數", "keyin" };
            
            string[] header1643 = { "分公司", "帳號", "組別", "交易員","履約日期","成交日期","委託單號","成交序號","拆單序號", "交易所", "商品代碼", "商品年月", "履約價", "CP", "BS", "口數", "交易稅幣別","交易稅","手續費幣別","手續費","交易幣別","權利金收支/履約盈虧","結算價"};
            string[] header1645 = { "市場別","分公司", "帳號", "組別", "交易員", "交易所", "平倉日期", "平倉成交日期", "平倉委託編號", "平倉成交序號", "平倉拆單序號", "被平成交日期", "被平委託編號", "被平成交序號", "被平拆單序號", "指定平倉碼", "互抵", "BS", "商品代號", "商品年月", "履約價 ", "CP", "被平商品代號", "平倉口數", "被平口數", "平倉成交價", "被平成交價", "平倉損益", "業務員代號", "幣別", "交易稅", "手續費", "平倉權利金", "被平權利金", "平倉場內編號", "被平場內編號", "平倉電子單號", "被平電子單號","貨幣匯率"};

            string[] header1655 = { "分公司", "帳號", "組別", "交易員","交易所", "商品代碼","年月","履約價","買賣權","市場別","新平倉","買賣別","委託單價","成交均價","委託量","成交量","交易日期","成交時間","委託書號","來源別","原委託流水號"};
           

            dgv2010.ColumnCount = header2010.Count();
            for (int i = 0; i < header2010.Count(); i++)
                dgv2010.Columns[i].HeaderText = header2010[i];

            dgv2011.ColumnCount = header2011.Count();
            for (int i = 0; i < header2011.Count(); i++)
                dgv2011.Columns[i].HeaderText = header2011[i];
            
            dgv3310.ColumnCount = header3310.Count();
            for (int i = 0; i < header3310.Count(); i++)
                dgv3310.Columns[i].HeaderText = header3310[i];

            dgv3311.ColumnCount = header3311.Count();
            for (int i = 0; i < header3311.Count(); i++)
                dgv3311.Columns[i].HeaderText = header3311[i];

            dgv1614.ColumnCount = header1614.Count();
            for (int i = 0; i < header1614.Count(); i++)
                dgv1614.Columns[i].HeaderText = header1614[i];

            dgv1616.ColumnCount = header1616.Count();
            for (int i = 0; i < header1616.Count(); i++)
                dgv1616.Columns[i].HeaderText = header1616[i];

            dgv1618.ColumnCount = header1618.Count();
            for (int i = 0; i < header1618.Count(); i++)
                dgv1618.Columns[i].HeaderText = header1618[i];
            
            dgv1624.ColumnCount = header1624.Count();
            for (int i = 0; i < header1624.Count(); i++)
                dgv1624.Columns[i].HeaderText = header1624[i];

            dgv1626.ColumnCount = header1626.Count();
            for (int i = 0; i < header1626.Count(); i++)
                dgv1626.Columns[i].HeaderText = header1626[i];

            dgv1631.ColumnCount = header1631.Count();
            for (int i = 0; i < header1631.Count(); i++)
                dgv1631.Columns[i].HeaderText = header1631[i];

            dgv1633.ColumnCount = header1633.Count();
            for (int i = 0; i < header1633.Count(); i++)
                dgv1633.Columns[i].HeaderText = header1633[i];

            dgv1635.ColumnCount = header1635.Count();
            for (int i = 0; i < header1635.Count(); i++)
                dgv1635.Columns[i].HeaderText = header1635[i];

            
            dgv3314.ColumnCount = header3314.Count();
            for (int i = 0; i < header3314.Count(); i++)
                dgv3314.Columns[i].HeaderText = header3314[i];

            dgv3315.ColumnCount = header3315.Count();
            for (int i = 0; i < header3315.Count(); i++)
                dgv3315.Columns[i].HeaderText = header3315[i];

            dgv1643.ColumnCount = header1643.Count();
            for (int i = 0; i < header1643.Count(); i++)
                dgv1643.Columns[i].HeaderText = header1643[i];

            dgv1645.ColumnCount = header1645.Count();
            for (int i = 0; i < header1645.Count(); i++)
                dgv1645.Columns[i].HeaderText = header1645[i];

            dgv1655.ColumnCount = header1655.Count();
            for (int i = 0; i < header1655.Count(); i++)
                dgv1655.Columns[i].HeaderText = header1655[i];
        }
        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {
            int i = tabControl1.SelectedIndex;
            switch (i)
            {
                case 1: tcResult.SelectedTab = tpOrderRtn; break;
                case 2: tcResult.SelectedTab = tpForderRtn; break;
                case 3: tcResult.SelectedTab = tp1616; break;
                default: tcResult.SelectedTab = tpMessage; break;

            }
        }
        #endregion

        #region 下單(國內)
        private void btnGenSymbol_Click(object sender, EventArgs e) {
            //請依您的需求增加各欄位的檢核(ex 欄位長度,合理性等等) ;  在此不做欄位檢核
            tb20Code.Text = GenFullSymbol();
        }
        private void btnOrder_Click(object sender, EventArgs e) {
            //請依您的需求自行增加下單欄位的檢核(ex 欄位長度/欄位值合法性 等等) ;  
            long  rtn = 0;
            #region 
            MARKET_FLAG MF = (cbMarket.SelectedIndex == 0) ? MARKET_FLAG.MF_FUT :
                (cbMarket.SelectedIndex == 1) ? MARKET_FLAG.MF_OPT :
                (cbMarket.SelectedIndex == 2) ? MARKET_FLAG.MF_FUT_FLEX :
                (cbMarket.SelectedIndex == 3) ? MARKET_FLAG.MF_OPT_FLEX :
                MARKET_FLAG.MF_FUT; 

            SIDE_FLAG SideFlag = (tbTSide.Text[0] == 'B') ? SIDE_FLAG.SF_BUY : SIDE_FLAG.SF_SELL;

            if (rbMulti.Checked )  //2019.1.2 Add: 國內複式單以 第二支腳為主 
                SideFlag = (tbTSide2.Text[0] == 'B') ? SIDE_FLAG.SF_BUY : SIDE_FLAG.SF_SELL;
            
            //PRICE_FLAG priceFlag = (cbMarketPrice.Checked) ? PRICE_FLAG.PF_MARKET : PRICE_FLAG.PF_SPECIFIED;
            PRICE_FLAG priceFlag = PRICE_FLAG.PF_SPECIFIED;
            if (rbMP.Checked) priceFlag = PRICE_FLAG.PF_MARKET;
            else if (rbPP.Checked) priceFlag = PRICE_FLAG.PF_MARKET_RANGE; //2014.4.2 ADD 一定範圍市價單 


            decimal Price;
            if (priceFlag == PRICE_FLAG.PF_SPECIFIED)
                Price = decimal.Parse(tbTPrice.Text);
            else Price = 0;
                

            TIME_IN_FORCE TIF = TIME_IN_FORCE.TIF_ROD;
            if (cbROD.Text == "FOK") TIF = TIME_IN_FORCE.TIF_FOK;
            if (cbROD.Text == "FOK") TIF = TIME_IN_FORCE.TIF_FOK;
            switch (cbROD.Text) {
                case "ROD": TIF = TIME_IN_FORCE.TIF_ROD; break;
                case "FOK": TIF = TIME_IN_FORCE.TIF_FOK; break;
                case "IOC": TIF = TIME_IN_FORCE.TIF_IOC; break;
                default:
                    MessageBox.Show("ROD/FOK/IOC 項目錯誤");
                    return;
            }
            ushort Qty = 0;
            try {
                Qty = ushort.Parse(tbTQty.Text);
            }
            catch {
                MessageBox.Show("口數輸入錯誤");
                return;
            }
            OFFICE_FLAG officeFlag = OFFICE_FLAG.OF_SPEEDY;
            POSITION_EFFECT pe;
            switch (cbOpen.SelectedIndex) {
                case 0: pe = POSITION_EFFECT.PE_OPEN; break;
                case 1: pe = POSITION_EFFECT.PE_CLOSE; break;
                case 2: pe = POSITION_EFFECT.PE_DAY_TRADE; break;
                case 3: pe = POSITION_EFFECT.PE_AUTO; break;
                default:
                    MessageBox.Show("倉別錯誤");
                    return;
            }
            ORDER_TYPE ordertype = ORDER_TYPE.OT_NEW;
            switch (cbFunc.SelectedIndex) {
                case 0: ordertype = ORDER_TYPE.OT_NEW; break;
                case 1: ordertype = ORDER_TYPE.OT_CANCEL; break;
                case 2: ordertype = ORDER_TYPE.OT_MODIFY_QTY; break;
                case 3: ordertype = ORDER_TYPE.OT_MODIFY_PRICE; break;
            }

            tb20Code.Text = GenFullSymbol();
            #endregion 
            //****注意: RequestID必須經由GetRequestID取得, 且不可重覆********
            long RequestId;

            string symbol = tb20Code.Text;
            RequestId = tfcom.GetRequestId();      //取得送單序號
            if (ordertype == ORDER_TYPE.OT_NEW)    //新單
                rtn = tfcom.Order(ORDER_TYPE.OT_NEW, MF, RequestId, tbTBrokerID.Text, tbTAccount.Text, tbTSubAccount.Text ,
                                         symbol /*tb20Code.Text*/ ,SideFlag  , priceFlag, Price, TIF, Qty, pe, officeFlag);
            else {
                //刪/改單
                rtn = tfcom.Order(ordertype, MF, RequestId, tbTBrokerID.Text, tbTAccount.Text, tbTSubAccount.Text.Trim(),
                               symbol , SideFlag, priceFlag, Price, TIF, Qty, pe, officeFlag, tbMWebID.Text, tbMCnt.Text, tbMOrderNo.Text);

            }
            if (rtn != 0)
                MessageBox.Show(tfcom.GetOrderErrMsg(rtn));

        }
        private string GenFullSymbol()
        {
            string fullsymbol = "";
            if ((cbMarket.SelectedIndex == 0)||(cbMarket.SelectedIndex == 2))
            { //期貨
                if (rbSingle.Checked)  //單式單
                    fullsymbol = tfcom.GenFutSymbol(tbTSymbol.Text, tbTComym.Text, "");
                else   //複式單
                    fullsymbol = tfcom.GenFutSymbol(tbTSymbol.Text, tbTComym.Text, tbTComym2.Text);
            }
            else
            {   //選擇權
                if (rbSingle.Checked)  //單式單
                    fullsymbol = tfcom.GenOptSymbol(tbTSymbol.Text, tbTComym.Text, tbTStrikePrice.Text, tbTCallPut.Text);
                else fullsymbol = tfcom.GenOptDoubleSymbol(tbTSymbol.Text, tbTComym.Text, tbTStrikePrice.Text, tbTCallPut.Text, tbTSide.Text, tbTComym2.Text, tbTStrikePrice2.Text, tbTCallPut2.Text, tbTSide2.Text);
            }
            return fullsymbol;

        }
        #endregion 

        #region 下單(國外)
        private void btnForder_Click(object sender, EventArgs e) {
            ORDER_KIND ordkind = ORDER_KIND.OK_CONTROL;
            ORDER_TYPE ordertype;
            ordertype = ORDER_TYPE.OT_NEW;
            switch (cbFFunc.Text[0]) {
                case 'O': ordertype = ORDER_TYPE.OT_NEW; break;
                case 'C': ordertype = ORDER_TYPE.OT_CANCEL; break;
                case 'M': ordertype = ORDER_TYPE.OT_MODIFY; break;
            }
            MARKET_FLAG mf;
            mf = MARKET_FLAG.MF_FUT;
            switch (cbFMarket.Text[0]) {
                case 'F': mf = MARKET_FLAG.MF_FUT; break;
                case 'O': mf = MARKET_FLAG.MF_OPT; break;
            }
            string exchange = cbExchange.Text;
            if (exchange.Contains(":"))
                exchange = exchange.Substring(0, exchange.IndexOf(':'));
            decimal strikeprice; strikeprice = decimal.Parse(tbStrikePrice.Text);
            decimal orderPrice = 0;
            decimal.TryParse(tbFPrice.Text, out orderPrice);
            decimal stopPrice; stopPrice = decimal.Parse(tbStopPrice.Text);
            int qty = Convert.ToInt32(tbQty.Text);
            char cp = tbFCP.Text[0];

            SIDE_FLAG bs;
            bs = SIDE_FLAG.SF_BUY;
            switch (tbBS.Text[0]) {
                case 'B': bs = SIDE_FLAG.SF_BUY; break;
                case 'S': bs = SIDE_FLAG.SF_SELL; break;
            }
            
            PRICE_FLAG pflag;
            pflag = PRICE_FLAG.PF_MARKET;
            switch (cbPF.Text[0]) {
                case '1': pflag = PRICE_FLAG.PF_MARKET; break;
                case '2': pflag = PRICE_FLAG.PF_SPECIFIED; break;
                case '3': pflag = PRICE_FLAG.PF_STOP_MARKET; break;
                case '4': pflag = PRICE_FLAG.PF_STOP_SPECIFIED; break;
            }
            char daytrade = cbDayTrade.Checked ? 'Y' : 'N';
            
            POSITION_EFFECT pe;
            pe = POSITION_EFFECT.PE_OPEN;
            switch (cbFOpen.Text[0]) {
                case 'O': pe = POSITION_EFFECT.PE_OPEN; break;
                case 'C': pe = POSITION_EFFECT.PE_CLOSE; break;
                case 'A': pe = POSITION_EFFECT.PE_AUTO; break;
            }
            TIME_IN_FORCE tif;
            tif = TIME_IN_FORCE.TIF_FOK;
            switch (cbFROD.Text[0]) {
                case 'F': tif = TIME_IN_FORCE.TIF_FOK; break;
                case 'I': tif = TIME_IN_FORCE.TIF_IOC; break;
                case 'R': tif = TIME_IN_FORCE.TIF_ROD; break;
            }

            //2014.11.24 複式單; 
            char isMLeg = cbMleg.Checked ? 'Y' : 'N';
            string symbol2 = ""; 
            SIDE_FLAG bs2 = SIDE_FLAG.SF_BUY ; 
            string ComYM2 = "" ; 
            decimal strikeprice2 = 0 ; 
            char cp2 = ' ' ;
            if (isMLeg == 'Y') {
                symbol2 = tbFSymbol2.Text.Trim();
                ComYM2 = tbFComym2.Text.Trim(); 
                switch (tbBS2.Text[0]) {
                    case 'B': bs2 = SIDE_FLAG.SF_BUY; break;
                    case 'S': bs2 = SIDE_FLAG.SF_SELL; break;
                }
                strikeprice2 = decimal.Parse(tbStrikePrice2.Text);
                
                cp2 = tbFCP2.Text[0];
            }
            //****注意: RequestID必須經由GetRequestID取得, 且不可重覆********
            long RequestId; 
            long rtn;
            RequestId = tfcom.GetRequestId();
            rtn = tfcom.FOrder(ordkind, ordertype, RequestId, mf, tbFBrokerID.Text, tbFAccount.Text, tbSubAccount.Text, exchange, tbFSymbol.Text,
                               tbFComym.Text, strikeprice, cp, bs, pflag, daytrade, pe, tif, orderPrice, stopPrice, qty, tbFIdno.Text,
                               tbFCM.Text, tbFFUTAccount.Text, tbOrgSource.Text, tbOrgSEQ.Text, tbOrgOrdNo.Text, tbTradeDate.Text, tbWEBID.Text, tbKeyIn.Text,
                                isMLeg, symbol2, bs2, ComYM2, strikeprice2,cp2);


            if (rtn != 0)
                MessageBox.Show(tfcom.GetOrderErrMsg(rtn));
        }
        #endregion 

        #region 帳務查詢
        private void btn1616_Click(object sender, EventArgs e) {
            string mk = (cbMK.Text == "國內") ? "I" : "O";

            tfcom.WriterLog(txtBrkid.Text.Trim() + txtAcct.Text.Trim() + txtTrader.Text); 
            long rtn = tfcom.RetrivePositionSum(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(), txtGroup.Text.Trim());
            dgv1616.Rows.Clear();
            tcResult.SelectedTab = tp1616; 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!"); 
        }
        private void btn1618_Click(object sender, EventArgs e) {
            string mk = (cbMK.Text == "國內") ? "I" : "O";
            long rtn = tfcom.RetrivePositionDetail(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(), txtGroup.Text.Trim());
            tcResult.SelectedTab = tp1618; 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!"); 
        }
        private void btn1614_Click(object sender, EventArgs e) {
            string mk = (cbMK.Text == "國內") ? "I" : "O";
            long rtn = tfcom.RetriveCOVER(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(),
                                        txtComid_T.Text.Trim(), txtComYM_T.Text.Trim(), txtStrikePrice_T.Text.Trim(), txtCP_T.Text.Trim(), tbExchange.Text.Trim(), txtGroup.Text.Trim());
            tcResult.SelectedTab = tp1614; 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!"); 
        }
        private void btn1624_Click(object sender, EventArgs e) {
            string mk = (cbMK.Text == "國內") ? "I" : "O";
            long reqid = tfcom.GetRequestId();  //可自行帶入,不重複即可
            long rtn = tfcom.RetriveCOVERDetail(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(),
                                        txtComid_T.Text.Trim(), txtComYM_T.Text.Trim(), txtStrikePrice_T.Text.Trim(), txtCP_T.Text.Trim(), tbExchange.Text.Trim(), reqid, txtGroup.Text.Trim());
            tcResult.SelectedTab = tp1624; 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!"); 
        }
        private void btn1626_Click(object sender, EventArgs e) {
            string mk = (cbMK.Text == "國內") ? "I" : "O";
            long rtn = tfcom.RetriveFMargin(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(), txtGroup.Text.Trim());
            tcResult.SelectedTab = tp1626; 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!"); 
        }
        private void btnStrikeData_Click(object sender, EventArgs e)  //1643
        {
            string mk = (cbMK.Text == "國內") ? "I" : "O";
            string stype = (cbStrikeType.Text == "到期履約") ? "1" : "2";  //1=到期履約 , 2=無效履約
            long rtn = tfcom.RetriveStrikeDetail(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(), txtGroup.Text.Trim(), stype, tbsdateb.Text.Trim(), tbsdatee.Text.Trim(), tbsexch.Text.Trim(), tbscomid.Text.Trim());
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!");

        }
        private void btnCoverH_Click(object sender, EventArgs e)  //1645
        {
            string mk = (cbMK.Text == "國內") ? "I" : "O";
            long rtn = tfcom.RetriveCoverDHistory(mk, txtBrkid.Text.Trim(), txtAcct.Text.Trim(), txtTrader.Text.Trim(), txtGroup.Text.Trim(), tbcdateb.Text.Trim(), tbcdatee.Text.Trim());
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!");

        }
     
        //2018.12 Add 大小台互抵功能
        private void btnReciprocate_Click(object sender, EventArgs e)  //1647
        {
            string bs = tbTXBS.Text.Substring(0, 1).ToUpper();
            SIDE_FLAG side = (bs.Equals("B")) ? SIDE_FLAG.SF_BUY : SIDE_FLAG.SF_SELL;
            int qty = 0;
            Int32.TryParse(tbTXQty.Text, out qty);
            long rtn = tfcom.SendReciprocateRequest(tbTXBrk.Text.Trim(), tbTXAcct.Text.Trim(), tbTXYM.Text.Trim(), side, qty);
            if (rtn == -1)
                MessageBox.Show("無權限!!!");

        }
        #endregion 

        #region 台外幣互轉&手續費&出金
        private void btnExCurrency_Click(object sender, EventArgs e)   //1628
        {
            long rtn;
            decimal Amt;
            decimal.TryParse(tbExAmt.Text, out Amt);
            if (Amt == 0)
            {
                MessageBox.Show("金額輸入錯誤");
                return;
            }
            tcResult.SelectedTab = tpMessage;
            Currency_Excode ce = (cbExKind.SelectedIndex == 0) ? Currency_Excode.CE_TOFOREIGN : Currency_Excode.CE_TONTD;
            rtn = tfcom.ExchangeCurrency(tbExBrokerid.Text, tbExAcctno.Text, ce, Amt) ; 
            string msg;
            switch (rtn)
            {
                case 0: msg = ""; break;
                case -1: msg = "尚未連線"; break;
                case -3: msg = "尚未安裝簽章元件"; break;
                case -4: msg = "無此帳號查詢權限"; break;
                case -13: msg = "找不到有效憑證"; break;
                default: msg = "Unknow Code: " + rtn; break;
            }
            if (msg != "")
                MessageBox.Show(msg);
        }
        private void button5_Click(object sender, EventArgs e)   //1631
        {
            long rtn = tfcom.RetriveServiceFee(txt1631brokerid.Text, txt1631acct.Text, txt1631trader.Text, txt1631g.Text);
            tcResult.SelectedTab = tp1631;
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!");
        }
        private void button6_Click(object sender, EventArgs e)
        {  //
            long rtn;
            decimal Amt;


            decimal.TryParse(wamt.Text, out Amt);
            if (Amt == 0)
            {
                MessageBox.Show("金額輸入錯誤");
                return;
            }
            tcResult.SelectedTab = tp1633;
            Withdraw_Kind wk = (rba.Checked) ? Withdraw_Kind.WK_APPLY : Withdraw_Kind.WK_CANCEL;
            
            string curr = wcurrency.Text.Substring(0, 3);

            //2022.1.21 因應外規,若帳號為委任狀態,必須輸入出金密碼;
            string pwd = tbwithdrawpwd.Text.Trim(); 
            rtn = tfcom.ApplyWithdraw(wborkerid.Text, wacct.Text, curr, Amt, wk, wwebid.Text, wseqno.Text,pwd );
            if (rtn != 0)
                MessageBox.Show(tfcom.GetOrderErrMsg(rtn));
        }
        private void button7_Click(object sender, EventArgs e)
        { //1635
            //存提類別: 保留欄位, 目前只提供 類別 "提" 的查詢; 
            Withdraw_Type wt = (cbtyp.Text == "C.存") ? Withdraw_Type.WT_C : Withdraw_Type.WT_D;

            long rtn = tfcom.RetriveWithdraw(cbm.Text, tbbrk.Text, tbact.Text, wt);
            tcResult.SelectedTab = tp1635;
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!");
        }
        #endregion 

        #region 其它
        private void btnAcct1_Click(object sender, EventArgs e)  //登入帳號查詢1
        {
            AddInfo(tfcom.Accounts);
        }

        private void btn_Click(object sender, EventArgs e) //下載商品檔
        {
            tfcom.RetriveProductDetail();
        }
        private void btnProList_Click(object sender, EventArgs e)//商品列表
        {
            List<string> list1801 ;//= new List<string>();
            list1801 = tfcom.GetProcuctBaseList();
            for (int i = 0; i < list1801.Count; i++) {
                AddInfo(list1801[i]);
            }
            list1801 = null; 
        }
        private void btnHot_Click(object sender, EventArgs e)  //熱門商品
        {
            AddInfo(tfcom.HotProdcuts);
        }

        private void btnGet1805_Click(object sender, EventArgs e)  //商品查詢
        {
            /* 國內期貨亦可使用: GetProductBase(string symbol)   ; 回傳 PT01801 (詳見文件); 
             * 為整合外期商品而新增 GetProductBase(3個參數) 如下: */
            PT01805 p1805 = new PT01805();
            p1805 = tfcom.GetProductBase(MARKET_KIND.MK_DOMESTIC, "", txtComID.Text.Trim() );
            AddInfo(p1805.ToLog());
        }
        private void btnProcInfo_Click(object sender, EventArgs e)  //商品明細查詢
        {
            PT01802 p1802 = new PT01802();
            p1802 = tfcom.GetProductInfo(txtComID.Text.Trim());
            if (p1802 != null)
                AddInfo(p1802.ToLog());

        }
        private void btnDList_Click(object sender, EventArgs e)//商品明細列表
        {
            List<PT01802> list1802 = new List<PT01802>();
            PT01802 p1802 = new PT01802();
            list1802 = tfcom.GetProcuctDetailList(txtComID.Text.Trim());
            for (int i = 0; i < list1802.Count; i++)
            {
                p1802 = list1802[i];
                AddInfo(p1802.ComId);
            }
            list1802 = null;
            p1802 = null;
        }
        private void btnPoint_Click(object sender, EventArgs e)  //履約價小數位數
        {
            int dec = tfcom.GetStrikePriceDecimal(MARKET_KIND.MK_DOMESTIC, "", txtComID.Text.Trim(), "0");
            AddInfo(dec.ToString());
        }

        private void btnPList_Click(object sender, EventArgs e)//類別列表
        {
            List<string> listkind = new List<string>();
            listkind = tfcom.GetProListAllKind();
            if (listkind != null)
            {
                for (int i = 0; i < listkind.Count; i++)
                {
                    AddInfo(listkind[i]);
                }
            }
            listkind = null;
        }
        private void btnskind_Click(object sender, EventArgs e)  //類別商品查詢
        {
            List<PIProList> listres = new List<PIProList>();
            string qstring = txtQProList.Text.Trim();
            ProListQueryField field;
            field = (ProListQueryField)cbProListField.SelectedIndex;
            listres = tfcom.GetProListByStockKind(field, qstring);
            if (listres != null)
            {
                for (int i = 0; i < listres.Count; i++)
                {
                    AddInfo(listres[i].StockCode + listres[i].StockNo + listres[i].StockName + listres[i].StockKind + "|" + listres[i].StockEKind + listres[i].StockEName);
                }
            }
            listres = null;
        }

        private void button14_Click(object sender, EventArgs e) //T+1商品檔下載
        {
            tfcom.RetriveProductDetailT1();
        }
        private void button15_Click(object sender, EventArgs e)//T+1商品列表
        {
            List<string> list1801;//= new List<string>();
            list1801 = tfcom.GetProcuctBaseListT1();
            for (int i = 0; i < list1801.Count; i++)
            {
                AddInfo(list1801[i]);
            }
            list1801 = null;
        }
        private void button16_Click(object sender, EventArgs e)//T+1商品查詢
        {
            /* 國內期貨亦可使用: GetProductBase(string symbol)   ; 回傳 PT01801 (詳見文件); 
             * 為整合外期商品而新增 GetProductBase(3個參數) 如下: */
            PT01805 p1805 = new PT01805();
            p1805 = tfcom.GetProductBaseT1(textBox4.Text.Trim());
            AddInfo(p1805.ToLog());
        }
        private void button12_Click(object sender, EventArgs e)//T+1商品列表
        {
            List<PT01802> list1802 = new List<PT01802>();
            PT01802 p1802 = new PT01802();
            list1802 = tfcom.GetProcuctDetailListT1(textBox4.Text.Trim());
            for (int i = 0; i < list1802.Count; i++)
            {
                p1802 = list1802[i];
                AddInfo(p1802.ComId);
            }
            list1802 = null;
            p1802 = null;
        }
        private void button13_Click(object sender, EventArgs e)//T+1商品明細查詢
        {
            PT01802 p1802 = new PT01802();
            p1802 = tfcom.GetProductInfoT1(textBox5.Text.Trim());
            if (p1802 != null)
                AddInfo(p1802.ToLog());
        }

        private void btnFList_Click(object sender, EventArgs e)  //外期商品列表
        {
            List<string> list = new List<string>();
            MARKET_FLAG ctype;
            if (rbF.Checked) ctype = MARKET_FLAG.MF_FUT; else ctype = MARKET_FLAG.MF_OPT;
            list = tfcom.GetProcuctBaseList(MARKET_KIND.MK_FOREIGN, ctype);
            for (int i = 0; i < list.Count; i++)
            {
                AddInfo(list[i]);
            }
            list = null;
        }
        private void btnQF_Click(object sender, EventArgs e)//外期商品查詢
        {
            PT01805 p1805 = new PT01805();
            MARKET_FLAG ctype;
            if (rbF.Checked) ctype = MARKET_FLAG.MF_FUT; else ctype = MARKET_FLAG.MF_OPT;
            //查詢時未帶入cytpe 時, 表示查詢期貨商品;
            p1805 = tfcom.GetProductBase(MARKET_KIND.MK_FOREIGN, txtExchange.Text.Trim(), txtFComid.Text.Trim(), ctype);
            //p1805 = tfcom.GetProductBase(MARKET_KIND.MK_FOREIGN, txtExchange.Text.Trim(), txtFComid.Text.Trim());
            AddInfo(p1805.ToLog());
        }
        private void btnQYm_Click(object sender, EventArgs e)   //外期商品年月
        {
            List<string> list = new List<string>();
            MARKET_FLAG ctype;
            if (rbF.Checked) ctype = MARKET_FLAG.MF_FUT; else ctype = MARKET_FLAG.MF_OPT;
            list = tfcom.GetComYM(ctype,txtExchange.Text.Trim(), txtFComid.Text.Trim());
            for (int i = 0; i < list.Count; i++) {
                AddInfo(list[i]);
            }
            list = null; 
        }
        private void btnPointF_Click(object sender, EventArgs e)  //外期履約價小數位數
        {
            int dec = tfcom.GetStrikePriceDecimal(MARKET_KIND.MK_FOREIGN, txtExchange.Text, txtFComid.Text.Trim(), "0");
            AddInfo(dec.ToString());
        }

        private void button1_Click(object sender, EventArgs e)   //公告查詢
        {
            Notice_Market nm = Notice_Market.NM_ALL;
            if (cbNM.Text[0] == 'F') nm = Notice_Market.NM_FUT; else if (cbNM.Text[0] == 'S') nm = Notice_Market.NM_STK;
            Notice_Kind nk = Notice_Kind.NK_ALL;
            if (cbNK.Text[0] == 'N') nk = Notice_Kind.NK_NORMAL; else if (cbNK.Text[0] == 'E') nk = Notice_Kind.NK_EMERGENCY;
            tfcom.RetriveNotice(nm, nk);
        }

        private void button4_Click(object sender, EventArgs e)   //查錯誤碼
        {
            int code = Convert.ToInt32(textBox1.Text);
            MessageBox.Show(tfcom.GetMessageMap(code));
        }

        #endregion 

       

        private void btn1657_Click(object sender, EventArgs e)
        {
            //1635
            //存提類別: 保留欄位, 目前只提供 類別 "提" 的查詢; 
            long rtn = tfcom.QueryWithdraw(cb1657Mkt.Text, tb1657brk.Text, tb1657Acct.Text, tb1657Date.Text); 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!");
        }

        private void btn1753_Click(object sender, EventArgs e)
        {
            long rtn = tfcom.QueryTraderPWDStatus(tb1753brk.Text, tb1753acct.Text, tb1753grp.Text, tb1753trader.Text); 
            if (rtn == -1)
                MessageBox.Show("無查詢權限!!!");
        }

        private void btnFEX_Click(object sender, EventArgs e)
        {
             List<PT01805> rtnData = tfcom.GetFlexProductList();
            for (int i = 0; i < rtnData.Count; i++) {
                AddInfo(rtnData[i].ToLog()); 
            }
        }

        private void btn1649_Click(object sender, EventArgs e)
        {
            long reqID = tfcom.GetRequestId();
            string brk = tb49Brk.Text;
            string acct = tb49acct.Text;
            string grp = tb49grp.Text;
            string subacct = tb49sub.Text;
            string exch = tb49exch.Text;

            string comid1 = tb49comid1.Text;
            string comym1 = tb49ym1.Text;
            decimal stkprice1 = 0; decimal.TryParse(tb49sprice1.Text, out stkprice1);
            char cp1 = (tb49cp1.Text== "" ) ? ' ' : tb49cp1.Text[0];
            SIDE_FLAG side1 = ((tb49bs1.Text.ToUpper()[0]) == 'B') ? SIDE_FLAG.SF_BUY : SIDE_FLAG.SF_SELL; 
            decimal dprice1 = 0; decimal.TryParse(tb49dprice1.Text, out dprice1);
            
            string comid2 = tb49comid2.Text;
            string comym2 = tb49ym2.Text;
            decimal stkprice2 = 0; decimal.TryParse(tb49sprice2.Text, out stkprice2);
            char cp2 = (tb49cp2.Text== "" ) ? ' ' : tb49cp2.Text[0];
            SIDE_FLAG side2 = ((tb49bs2.Text.ToUpper()[0]) == 'B') ? SIDE_FLAG.SF_BUY : SIDE_FLAG.SF_SELL; 
            decimal dprice2 = 0; decimal.TryParse(tb49dprice2.Text, out dprice2);
            
            int qty = 0; int.TryParse(tb49Qty.Text,out qty) ;
            long rtn = tfcom.ApplyNetOffsetCover(reqID, brk, acct, grp, subacct, exch, comid1, comym1, stkprice1, cp1, side1, comid2, comym2, stkprice2, cp2, side2, qty, dprice1, dprice2);
            string msg = (rtn == 0) ? "已送出" :  tfcom.GetOrderErrMsg(rtn);
            AddInfo("1649 批次互抵&指定平倉申請: " + msg); 
        }

        private void btn1665_Click(object sender, EventArgs e)
        {
            long reqID = tfcom.GetRequestId();
            string brk = tb65Brk.Text;
            string acct = tb65acct.Text;
            string exch = tb65exch.Text;

            string comid = tb65comid.Text;
            string comym = tb65ym.Text;
            decimal stkprice = 0; decimal.TryParse(tb65sprice.Text, out stkprice);
            char cp = tb65cp.Text[0];
            string date1 = mb65Date1.Text;
            string ordno1 = tb65Ordno1.Text;
            string matno1 = tb65Mno1.Text;
            string seq1 = tb65Seq1.Text;

            string date2 = mb65Date2.Text;
            string ordno2 = tb65Ordno2.Text;
            string matno2 = tb65Mno2.Text;
            string seq2 = tb65Seq2.Text;
            int qty = 0; int.TryParse(tb65Qty.Text, out qty);
            long rtn = tfcom.ApplyNetCover(reqID, brk, acct, exch, comid, comym, stkprice, cp, date1, ordno1, matno1, seq1, date2, ordno2, matno2, seq2, qty);
            string msg = (rtn == 0) ? "已送出" : tfcom.GetOrderErrMsg(rtn);
            AddInfo("1665 網路指定平倉申請: " + msg); 
        }
        //網路拆組申請 
        private void btn1667_Click(object sender, EventArgs e)
        {
            long reqID = tfcom.GetRequestId();
            string brk = tb67Brk.Text;
            string acct = tb67acct.Text;
            char kind = cb67Kind.Text[0] ;
            bool bspecific = ((kind == '1') || (kind == '3'));
            string date1 = (bspecific) ? mb67Date1.Text : ""; 
            string ordno1 =(bspecific) ?  tb67Ordno1.Text: "" ; 
            string matno1 =(bspecific) ?  tb67Mno1.Text: "" ;
            string seq1 = (bspecific) ? tb67Seq1.Text : "";

            string date2 = (bspecific) ? mb67Date2.Text : ""; 
            string ordno2 = (bspecific) ? tb67Ordno2.Text: "" ; 
            string matno2 = (bspecific) ? tb67Mno2.Text: "" ;
            string seq2 = (bspecific) ? tb67Seq2.Text : "";
            int qty = 0; int.TryParse(tb67qty.Text, out qty);
            long rtn = tfcom.ApplyNetAssembly(reqID, brk, acct,kind, date1, ordno1, matno1, seq1, date2, ordno2, matno2, seq2, qty);
            string msg = (rtn == 0) ? "已送出" : tfcom.GetOrderErrMsg(rtn);
            AddInfo("1667 網路拆組申請: " + msg); 
        }

        private void btn1669_Click(object sender, EventArgs e)
        {
            long reqID = tfcom.GetRequestId();
            long rtn = tfcom.ApplyNetAssemCover(reqID, tb69brk.Text, tb69acct.Text);
            string msg = (rtn == 0) ? "已送出" : tfcom.GetOrderErrMsg(rtn);
            AddInfo("1669 網路部分拆平組申請: " + msg); 
        }

        
      
    

    }

        
}
