Ejemplo n.º 1
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="pInstrument"></param>
 /// <param name="pDirection"></param>
 /// <param name="pOffset"></param>
 /// <param name="pPrice"></param>
 /// <param name="pVolume"></param>
 /// <param name="pHedge"></param>
 /// <returns>正确返回0</returns>
 public int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, HedgeType pHedge = HedgeType.Speculation, OrderType pType = OrderType.Limit)
 {
     return _proxy.ReqOrderInsert(pInstrument, pDirection, pOffset, pPrice, pVolume, pHedge, pType);
 }
Ejemplo n.º 2
0
        private void CTPOnRspQryInvestorPosition(ref CThostFtdcInvestorPositionField pInvestorPosition, ref CThostFtdcRspInfoField pRspInfo, int nRequestID, bool bIsLast)
        {
            if (!string.IsNullOrEmpty(pInvestorPosition.InstrumentID))
            {
                var f = pInvestorPosition;
                _listPosi.Add(f);
            }

            if (bIsLast)
            {
                foreach (var g in _listPosi.GroupBy(p => p.InstrumentID + "_" + p.PosiDirection))
                {
                    var id = g.First();
                    //整理持仓数据
                    HedgeType hedge = HedgeType.Speculation;
                    switch (id.HedgeFlag)
                    {
                    case TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation:
                        hedge = HedgeType.Speculation;
                        break;

                    case TThostFtdcHedgeFlagType.THOST_FTDC_HF_Arbitrage:
                        hedge = HedgeType.Arbitrage;
                        break;

                    case TThostFtdcHedgeFlagType.THOST_FTDC_HF_Hedge:
                        hedge = HedgeType.Hedge;
                        break;
                    }

                    DirectionType dire = DirectionType.Buy;
                    if (g.First().PosiDirection == TThostFtdcPosiDirectionType.THOST_FTDC_PD_Short)
                    {
                        dire = DirectionType.Sell;
                    }
                    var key = id.InstrumentID + "_" + dire;
                    var pf  = DicPositionField.GetOrAdd(key, new PositionField
                    {
                        InstrumentID = id.InstrumentID,
                        Direction    = dire,
                        Hedge        = hedge,
                    });

                    //if (pInvestorPosition.PositionDate == TThostFtdcPositionDateType.THOST_FTDC_PSD_Today)
                    //{
                    //	pf.TdPosition = pInvestorPosition.Position;
                    //	pf.TdCost = pf.TdPosition == 0 ? 0 : (pInvestorPosition.PositionCost  /*pInvestorPosition.TodayPosition * pf.TdPosition*/);
                    //}
                    //if (pInvestorPosition.PositionDate == TThostFtdcPositionDateType.THOST_FTDC_PSD_History)
                    //{
                    //	pf.YdPosition = pInvestorPosition.Position;
                    //	pf.YdCost = pInvestorPosition.PreSettlementPrice * pf.YdPosition * DicInstrumentField[pf.InstrumentID].VolumeMultiple;
                    //	//pf.YdCost = pInvestorPosition.PositionCost / pInvestorPosition.YdPosition * pf.YdPosition;
                    //}
                    pf.Position   = g.Sum(n => n.Position);                  // pf.TdPosition + pf.YdPosition;
                    pf.TdPosition = g.Sum(n => n.TodayPosition);
                    pf.YdPosition = pf.Position - pf.TdPosition;             // g.Sum(n => n.YdPosition);

                    pf.Price          = pf.Position <= 0 ? 0 : (g.Sum(n => n.PositionCost) / DicInstrumentField[pf.InstrumentID].VolumeMultiple / pf.Position);
                    pf.CloseProfit    = g.Sum(n => n.CloseProfit);
                    pf.PositionProfit = g.Sum(n => n.PositionProfit);
                    pf.Commission     = g.Sum(n => n.Commission);
                    pf.Margin         = g.Sum(n => n.UseMargin);
                }

                TradingAccount.CloseProfit    = _listPosi.Sum(n => n.CloseProfit);
                TradingAccount.PositionProfit = _listPosi.Sum(n => n.PositionProfit);
                TradingAccount.Commission     = _listPosi.Sum(n => n.Commission);
                TradingAccount.Fund           = TradingAccount.PreBalance + TradingAccount.CloseProfit + TradingAccount.PositionProfit - TradingAccount.Commission;

                TradingAccount.FrozenCash = _listPosi.Sum(n => n.FrozenCash);
                //由查帐户资金函数处理,原因:保证金有单边收的情况无法用持仓统计
                //TradingAccount.CurrMargin = _listPosi.Sum(n => n.UseMargin);
                //TradingAccount.Available = TradingAccount.Fund - TradingAccount.CurrMargin - TradingAccount.FrozenCash;
                //TradingAccount.Risk = TradingAccount.CurrMargin / TradingAccount.Fund;

                _listPosi.Clear();                //清除,以便得到结果是重新添加
            }
        }
Ejemplo n.º 3
0
        public override int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, int pCustom, OrderType pType = OrderType.Limit, HedgeType pHedge = HedgeType.Speculation)
        {
            //限价
            var OrderPriceType  = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice;
            var TimeCondition   = TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD;
            var VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV;

            if (pType == OrderType.Market)             //市价
            {
                OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice;
                TimeCondition  = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC;
                //max = instField.MaxMarketOrderVolume;
                pPrice = 0;
            }
            else if (pType == OrderType.FAK)             //FAK
            {
                OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice;
                TimeCondition  = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC;
            }
            else if (pType == OrderType.FOK)             //FOK
            {
                OrderPriceType  = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice;
                TimeCondition   = TThostFtdcTimeConditionType.THOST_FTDC_TC_IOC;
                VolumeCondition = TThostFtdcVolumeConditionType.THOST_FTDC_VC_CV;                 //全部数量
            }

            return((int)_t.ReqOrderInsert(_broker, _investor, InstrumentID: pInstrument,
                                          OrderRef: string.Format("{0:000000}{1:000000}", _ref++, pCustom % 1000000),
                                          CombHedgeFlag: new string((char)(pHedge == HedgeType.Speculation ? TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation : pHedge == HedgeType.Arbitrage ? TThostFtdcHedgeFlagType.THOST_FTDC_HF_Arbitrage : TThostFtdcHedgeFlagType.THOST_FTDC_HF_Hedge), 1),
                                          CombOffsetFlag: new String((char)(pOffset == OffsetType.Open ? TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open : pOffset == OffsetType.Close ? TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close : TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday), 1),
                                          Direction: pDirection == DirectionType.Buy ? TThostFtdcDirectionType.THOST_FTDC_D_Buy : TThostFtdcDirectionType.THOST_FTDC_D_Sell,
                                          VolumeTotalOriginal: pVolume,
                                          ForceCloseReason: TThostFtdcForceCloseReasonType.THOST_FTDC_FCC_NotForceClose,
                                          ContingentCondition: TThostFtdcContingentConditionType.THOST_FTDC_CC_Immediately,
                                          VolumeCondition: VolumeCondition,
                                          LimitPrice: pPrice,
                                          IsSwapOrder: 0,
                                          MinVolume: 1,
                                          UserForceClose: 0,
                                          TimeCondition: TimeCondition,
                                          OrderPriceType: OrderPriceType));
        }
Ejemplo n.º 4
0
 internal FuzzyCondition(FuzzyVariable var, FuzzyTerm term, bool not, HedgeType hedge)
     : base(var, term, not)
 {
     _hedge = hedge;
 }
Ejemplo n.º 5
0
        static private List <IExpression> ExtractSingleCondidtions(List <IExpression> conditionExpression, List <FuzzyVariable> input, Dictionary <string, Lexem> lexems)
        {
            List <IExpression> copyExpressions = conditionExpression.GetRange(0, conditionExpression.Count);
            List <IExpression> expressions     = new List <IExpression>();

            while (copyExpressions.Count > 0)
            {
                if (copyExpressions[0] is VarLexem <FuzzyVariable> )
                {
                    //
                    // Разбор переменной
                    //
                    VarLexem <FuzzyVariable> varLexem = (VarLexem <FuzzyVariable>)copyExpressions[0];
                    if (copyExpressions.Count < 3)
                    {
                        throw new Exception(string.Format("Состояние начинается с '{0}' не корректно.", varLexem.Text));
                    }

                    if (varLexem.Input == false)
                    {
                        throw new Exception("Переменная в состоянии должна быть входной переменной.");
                    }

                    //
                    // Разбор "is" лексемы
                    //
                    Lexem exprIs = (Lexem)copyExpressions[1];
                    if (exprIs != lexems["is"])
                    {
                        throw new Exception(string.Format("'is' ключевое слово должно идти после {0} идентификатора.", varLexem.Text));
                    }


                    //
                    // Разбор 'not' лексемы (если существует)
                    //
                    int  cur = 2;
                    bool not = false;
                    if (copyExpressions[cur] == lexems["not"])
                    {
                        not = true;
                        cur++;

                        if (copyExpressions.Count <= cur)
                        {
                            throw new Exception("Ошибка около 'not' в состоянии части правила.");
                        }
                    }

                    //"slightly"    - немного
                    //"somewhat"    - в некотором роде
                    //"very"        - очень
                    //"extremely"   - чрезвычайно

                    //
                    // Разбор hedge модификатора (если существует)
                    //
                    HedgeType hedge = HedgeType.None;
                    if (copyExpressions[cur] == lexems["slightly"])
                    {
                        hedge = HedgeType.Slightly;
                    }
                    else if (copyExpressions[cur] == lexems["somewhat"])
                    {
                        hedge = HedgeType.Somewhat;
                    }
                    else if (copyExpressions[cur] == lexems["very"])
                    {
                        hedge = HedgeType.Very;
                    }
                    else if (copyExpressions[cur] == lexems["extremely"])
                    {
                        hedge = HedgeType.Extremely;
                    }

                    if (hedge != HedgeType.None)
                    {
                        cur++;

                        if (copyExpressions.Count <= cur)
                        {
                            throw new Exception(string.Format("Ошибка около '{0}' в состоянии части правила.", hedge.ToString().ToLower()));
                        }
                    }

                    //
                    // Разбор терма
                    //
                    Lexem exprTerm = (Lexem)copyExpressions[cur];
                    if (!(exprTerm is IAltLexem))
                    {
                        throw new Exception(string.Format("Неверный идентификатор '{0}' в стостоянии части правила.", exprTerm.Text));
                    }
                    IAltLexem             altLexem  = (IAltLexem)exprTerm;
                    TermLexem <FuzzyTerm> termLexem = null;
                    do
                    {
                        if (!(altLexem is TermLexem <FuzzyTerm>))
                        {
                            continue;
                        }

                        termLexem = (TermLexem <FuzzyTerm>)altLexem;
                        if (!varLexem.Var.Values.Contains(termLexem.Term))
                        {
                            termLexem = null;
                            continue;
                        }
                    }while ((altLexem = altLexem.Alternative) != null && termLexem == null);

                    if (termLexem == null)
                    {
                        throw new Exception(string.Format("Неверный идентификатор '{0}' в стостоянии части правила.", exprTerm.Text));
                    }

                    //
                    // Добавление нового выражения состояния
                    //
                    FuzzyCondition condition = new FuzzyCondition(varLexem.Var, termLexem.Term, not, hedge);
                    expressions.Add(new ConditionExpression(copyExpressions.GetRange(0, cur + 1), condition));
                    copyExpressions.RemoveRange(0, cur + 1);
                }
                else
                {
                    IExpression expr = copyExpressions[0];
                    if (expr == lexems["and"] ||
                        expr == lexems["or"] ||
                        expr == lexems["("] ||
                        expr == lexems[")"])
                    {
                        expressions.Add(expr);
                        copyExpressions.RemoveAt(0);
                    }
                    else
                    {
                        Lexem unknownLexem = (Lexem)expr;
                        throw new Exception(string.Format("Лексема  '{0}' найдена в ошибочном месте в состоянии части правила.", unknownLexem.Text));
                    }
                }
            }

            return(expressions);
        }
Ejemplo n.º 6
0
        public int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, OrderType pType = OrderType.Limit, int pCustom = 0, HedgeType pHedge = HedgeType.Speculation)
        {
            InstrumentField    dif;
            ExchangeStatusType es;

            //小节收盘:等待重新开盘
            if (DicInstrumentField.TryGetValue(pInstrument, out dif))
            {
                if (_initFlow)
                {
                    pPrice += _floConfig.FirstAddTicks * (pDirection == DirectionType.Buy ? 1 : -1) * dif.PriceTick;
                }
                //限定在涨跌板范围内
                MarketData f;
                if (_q == null)
                {
                    ShowInfo("行情接口异常");
                    return(-1);
                }
                if (!_q.DicTick.TryGetValue(pInstrument, out f))
                {
                    _q.ReqSubscribeMarketData(pInstrument);
                    Thread.Sleep(200);
                }
                if (!_q.DicTick.TryGetValue(pInstrument, out f))
                {
                    ShowInfo($"合约{pInstrument}无行情");
                    return(-1);
                }

                pPrice = Math.Max(f.LowerLimitPrice, Math.Min(f.UpperLimitPrice, pPrice));
                //下单前修正价格为最小变动的倍数
                pPrice = (int)(pPrice / dif.PriceTick) * dif.PriceTick;

                if (DicExcStatus.TryGetValue(dif.ProductID, out es) || DicExcStatus.TryGetValue(dif.InstrumentID, out es) || DicExcStatus.TryGetValue(dif.ExchangeID.ToString(), out es))
                {
                    if (es == ExchangeStatusType.NoTrading)                    //小节收盘中:待处理
                    {
                        ShowInfo($"小节收盘,待重新开盘后再发委托:{pInstrument},{pDirection},{ pOffset},{ pPrice},{ pVolume},{pCustom}");
                        _listWaitTrading.Add(new object[] { pInstrument, pDirection, pOffset, pPrice, pVolume, pType, pCustom, pHedge });
                        return(0);
                    }
                }
            }
            return(base.ReqOrderInsert(pInstrument, pDirection, pOffset, pPrice, pVolume, pCustom, pType, pHedge));
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Create a single condition
 /// </summary>
 /// <param name="var">A linguistic variable to which the condition is related</param>
 /// <param name="term">A term in expression 'var is term'</param>
 /// <param name="not">Does condition contain 'not'</param>
 /// <param name="hedge">Hedge modifier</param>
 /// <returns>Generated condition</returns>
 public FuzzyCondition CreateCondition(FuzzyVariable var, FuzzyTerm term, bool not, HedgeType hedge)
 {
     return(new FuzzyCondition(var, term, not, hedge));
 }
Ejemplo n.º 8
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="pInstrument"></param>
 /// <param name="pDirection"></param>
 /// <param name="pOffset"></param>
 /// <param name="pPrice"></param>
 /// <param name="pVolume"></param>
 /// <param name="pHedge"></param>
 /// <returns>正确返回0</returns>
 public int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, HedgeType pHedge = HedgeType.Speculation, OrderType pType = OrderType.Limit, string pCustom = "HFapi")
 {
     return(_proxy.ReqOrderInsert(pInstrument, pDirection, pOffset, pPrice, pVolume, pHedge, pType, pCustom));
 }
Ejemplo n.º 9
0
 /// <summary>
 /// 委托
 /// </summary>
 /// <param name="pInstrument">合约</param>
 /// <param name="pDirection">买卖</param>
 /// <param name="pOffset">开平</param>
 /// <param name="pPrice">价格</param>
 /// <param name="pVolume">数量</param>
 /// <param name="pType">委托类型</param>
 /// <param name="pCustom">自定义字段(6位数字)</param>
 /// <param name="pHedge">投保</param>
 /// <returns></returns>
 public abstract int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, int pCustom, OrderType pType = OrderType.Limit, HedgeType pHedge = HedgeType.Speculation);
 private static decimal GetCurrentLevel(ForwardContract contract, HedgeType hedgeType)
 {
     return(contract == null ? 0M : hedgeType == HedgeType.Investment ? -contract.Cover : contract.Cover);
 }
Ejemplo n.º 11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="pInstrument"></param>
 /// <param name="pDirection"></param>
 /// <param name="pOffset"></param>
 /// <param name="pPrice">价格</param>
 /// <param name="pVolume"></param>
 /// <param name="pHedge"></param>
 /// <param name="pType">报单类型</param>
 /// <returns></returns>
 public int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, HedgeType pHedge, OrderType pType, string pCustom)
 {
     return(((DefReqOrderInsert)Invoke(this._handle, "ReqOrderInsert", typeof(DefReqOrderInsert)))(pInstrument, pDirection, pOffset, pPrice, pVolume, pHedge, pType, pCustom));
 }
Ejemplo n.º 12
0
        static private List <IExpression> ExtractSingleCondidtions(List <IExpression> conditionExpression, List <FuzzyVariable> input, Dictionary <string, Lexem> lexems)
        {
            List <IExpression> copyExpressions = conditionExpression.GetRange(0, conditionExpression.Count);
            List <IExpression> expressions     = new List <IExpression>();

            while (copyExpressions.Count > 0)
            {
                if (copyExpressions[0] is VarLexem <FuzzyVariable> )
                {
                    //
                    // Parse variable
                    //
                    VarLexem <FuzzyVariable> varLexem = (VarLexem <FuzzyVariable>)copyExpressions[0];
                    if (copyExpressions.Count < 3)
                    {
                        throw new Exception(string.Format("Condition strated with '{0}' is incorrect.", varLexem.Text));
                    }

                    if (varLexem.Input == false)
                    {
                        throw new Exception("The variable in condition part must be an input variable.");
                    }

                    //
                    // Parse 'is' lexem
                    //
                    Lexem exprIs = (Lexem)copyExpressions[1];
                    if (exprIs != lexems["is"])
                    {
                        throw new Exception(string.Format("'is' keyword must go after {0} identifier.", varLexem.Text));
                    }


                    //
                    // Parse 'not' lexem (if exists)
                    //
                    int  cur = 2;
                    bool not = false;
                    if (copyExpressions[cur] == lexems["not"])
                    {
                        not = true;
                        cur++;

                        if (copyExpressions.Count <= cur)
                        {
                            throw new Exception("Error at 'not' in condition part of the rule.");
                        }
                    }

                    //"slightly"
                    //"somewhat"
                    //"very"
                    //"extremely"

                    //
                    // Parse hedge modifier (if exists)
                    //
                    HedgeType hedge = HedgeType.None;
                    if (copyExpressions[cur] == lexems["slightly"])
                    {
                        hedge = HedgeType.Slightly;
                    }
                    else if (copyExpressions[cur] == lexems["somewhat"])
                    {
                        hedge = HedgeType.Somewhat;
                    }
                    else if (copyExpressions[cur] == lexems["very"])
                    {
                        hedge = HedgeType.Very;
                    }
                    else if (copyExpressions[cur] == lexems["extremely"])
                    {
                        hedge = HedgeType.Extremely;
                    }

                    if (hedge != HedgeType.None)
                    {
                        cur++;

                        if (copyExpressions.Count <= cur)
                        {
                            throw new Exception(string.Format("Error at '{0}' in condition part of the rule.", hedge.ToString().ToLower()));
                        }
                    }

                    //
                    // Parse term
                    //
                    Lexem exprTerm = (Lexem)copyExpressions[cur];
                    if (!(exprTerm is IAltLexem))
                    {
                        throw new Exception(string.Format("Wrong identifier '{0}' in conditional part of the rule.", exprTerm.Text));
                    }

                    IAltLexem             altLexem  = (IAltLexem)exprTerm;
                    TermLexem <FuzzyTerm> termLexem = null;
                    do
                    {
                        if (!(altLexem is TermLexem <FuzzyTerm>))
                        {
                            continue;
                        }

                        termLexem = (TermLexem <FuzzyTerm>)altLexem;
                        if (!varLexem.Var.Values.Contains(termLexem.Term))
                        {
                            termLexem = null;
                            continue;
                        }
                    }while ((altLexem = altLexem.Alternative) != null && termLexem == null);

                    if (termLexem == null)
                    {
                        throw new Exception(string.Format("Wrong identifier '{0}' in conditional part of the rule.", exprTerm.Text));
                    }

                    //
                    // Add new condition expression
                    //
                    FuzzyCondition condition = new FuzzyCondition(varLexem.Var, termLexem.Term, not, hedge);
                    expressions.Add(new ConditionExpression(copyExpressions.GetRange(0, cur + 1), condition));
                    copyExpressions.RemoveRange(0, cur + 1);
                }
                else
                {
                    IExpression expr = copyExpressions[0];
                    if (expr == lexems["and"] ||
                        expr == lexems["or"] ||
                        expr == lexems["("] ||
                        expr == lexems[")"])
                    {
                        expressions.Add(expr);
                        copyExpressions.RemoveAt(0);
                    }
                    else
                    {
                        Lexem unknownLexem = (Lexem)expr;
                        throw new Exception(string.Format("Lexem '{0}' found at the wrong place in condition part of the rule.", unknownLexem.Text));
                    }
                }
            }

            return(expressions);
        }
Ejemplo n.º 13
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="pInstrument"></param>
		/// <param name="pDirection"></param>
		/// <param name="pOffset"></param>
		/// <param name="pPrice">价格</param>
		/// <param name="pVolume"></param>
		/// <param name="pHedge"></param>
		/// <param name="pType">报单类型</param>
		/// <returns></returns>
		public int ReqOrderInsert(string pInstrument, DirectionType pDirection, OffsetType pOffset, double pPrice, int pVolume, HedgeType pHedge, OrderType pType, string pCustom)
		{
			return ((DefReqOrderInsert)Invoke(this._handle, "ReqOrderInsert", typeof(DefReqOrderInsert)))(pInstrument, pDirection, pOffset, pPrice, pVolume, pHedge, pType, pCustom);
		}
Ejemplo n.º 14
0
 public WallPiece createHedge(int i, int j, HedgeType hedge)
 {
     switch(hedge)
     {
         case HedgeType.horizontal : {return new WallPiece(i, j, hedgeTexture, Color.Brown, this); }
         case HedgeType.vertical: { return new WallPiece(i, j, hedgeVertTexture, Color.Brown, this); }
         case HedgeType.corner_topleft: { return new WallPiece(i, j, hedgeCornerTexturetl, Color.Brown, this); }
         case HedgeType.corner_topright: { return new WallPiece(i, j, hedgeCornerTexturetr, Color.Brown, this); }
         case HedgeType.corner_bottomleft: { return new WallPiece(i, j, hedgeCornerTexturebl, Color.Brown, this); }
         case HedgeType.corner_bottomright: { return new WallPiece(i, j, hedgeCornerTexturebr, Color.Brown, this); }
         case HedgeType.crisscross: { return new WallPiece(i, j, hedgeCrossTexture, Color.Brown, this); }
         default: return null;
     }
 }