public static bool HasOrderExecuted( IBroker broker, string stockCode, int quantity, double price, OrderPriceType orderType, OrderDirection orderDirection, InstrumentType instrumentType, DateTime expiryDate, out string orderReferenceNumber) { orderReferenceNumber = null; string contract = String.Empty; string strExpDate = expiryDate.ToString("dd-MMM-yyyy"); if (instrumentType == InstrumentType.FutureIndex || instrumentType == InstrumentType.FutureStock) { contract += "FUT-"; } else { throw new NotSupportedException(); } contract += (stockCode + "-" + strExpDate); // this loop is there just for potential retry purpose for (int count = 1; count <= 2; count++) { Dictionary <string, DerivativeTradeBookRecord> trades; BrokerErrorCode errorCode = broker.GetDerivativesTradeBook(DateTime.Now, DateTime.Now, instrumentType, true, out trades); if (!errorCode.Equals(BrokerErrorCode.Success)) { return(false); } foreach (DerivativeTradeBookRecord singleTrade in trades.Values) { if (singleTrade.ContractName.ToUpperInvariant() != contract.ToUpperInvariant()) { continue; } if (singleTrade.Quantity != quantity) { continue; } if (singleTrade.Direction != orderDirection) { continue; } orderReferenceNumber = singleTrade.OrderRefenceNumber; return(true); } } return(false); }
/// <summary> /// создать закрывающий ордер для сделки /// </summary> public Order CreateCloseOrderForDeal(Position deal, decimal price, OrderPriceType priceType, TimeSpan timeLife) { Side direction; if (deal.Direction == Side.Buy) { direction = Side.Sell; } else { direction = Side.Buy; } int volume = deal.OpenVolume; if (volume == 0) { return(null); } Order newOrder = new Order(); newOrder.NumberUser = NumberGen.GetNumberOrder(); newOrder.Side = direction; newOrder.Price = price; newOrder.Volume = volume; newOrder.TypeOrder = priceType; newOrder.LifeTime = timeLife; return(newOrder); }
/// <summary> /// создать ордер /// </summary> public Order CreateOrder(Side direction, decimal priceOrder, int volume, OrderPriceType priceType, TimeSpan timeLife) { Order newOrder = new Order(); newOrder.NumberUser = NumberGen.GetNumberOrder(); newOrder.Side = direction; newOrder.Price = priceOrder; newOrder.Volume = volume; newOrder.TypeOrder = priceType; newOrder.LifeTime = timeLife; return(newOrder); }
public BrokerErrorCode ModifyEquityOrder(string stockCode, int quantity, string price, OrderPriceType orderPriceType, OrderDirection orderDirection, EquityOrderType orderType, Exchange exchange, string settlementNumber, out string orderRef) { orderRef = null; return(BrokerErrorCode.Success); }
/// <summary> /// Parses a price in Kraken format. /// </summary> /// <example><c>"123.123"</c> parses to an absolute price of <c>123.123</c>.</example> /// <example><c>"+5"</c> parses to the relative price of +5.</example> /// <example><c>"+5%"</c> parses to the relative price of +5%.</example> /// <remarks>See the Kraken documentation for information about order price specifications.</remarks> public static OrderPrice Parse(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Value must not be empty or white-space only"); } value = value.Trim(); OrderPriceType type = OrderPriceType.Absolute; switch (value[0]) { case '+': type = OrderPriceType.Add; break; case '-': type = OrderPriceType.Subtract; break; case '#': type = OrderPriceType.AddOrSubtract; break; } bool pct = false; if (value[value.Length - 1] == '%') { if (type == OrderPriceType.Absolute) { throw new ArgumentException("Percentages can only be specified as relative values", nameof(value)); } type++; pct = true; } int start = type == OrderPriceType.Absolute ? 0 : 1; int end = pct ? value.Length - 1 : value.Length; string amountSubstring = value.Substring(start, end - start); if (!decimal.TryParse(amountSubstring, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal amount)) { throw new ArgumentException($"Could not parse value {amountSubstring} as a number", nameof(value)); } return(new OrderPrice(type, amount)); }
/// <summary> /// create order / /// создать ордер /// </summary> public Order CreateOrder( Side direction, decimal priceOrder, decimal volume, OrderPriceType priceType, TimeSpan timeLife, StartProgram startProgram, OrderPositionConditionType positionConditionType) { Order newOrder = new Order(); newOrder.NumberUser = NumberGen.GetNumberOrder(startProgram); newOrder.Side = direction; newOrder.Price = priceOrder; newOrder.Volume = volume; newOrder.TypeOrder = priceType; newOrder.LifeTime = timeLife; newOrder.PositionConditionType = positionConditionType; return(newOrder); }
public BrokerErrorCode PlaceEquityOrder(string stockCode, OrderPositionTypeEnum holdingType, int availableQty, int quantity, string price, OrderPriceType orderPriceType, OrderDirection orderDirection, EquityOrderType orderType, Exchange exchange, string settlementNumber, out string orderRef) { BrokerErrorCode errCode = BrokerErrorCode.Unknown; orderRef = ""; // Only OrderPositionTypeEnum.Margin is Buy/Sell, rest all others are only sell orders if (holdingType == OrderPositionTypeEnum.Btst) // only a sell order { errCode = broker.PlaceEquityDeliveryBTSTOrder(stockCode, quantity, price, orderPriceType, orderDirection, orderType, exchange, settlementNumber, out orderRef); } else if (holdingType == OrderPositionTypeEnum.Demat || holdingType == OrderPositionTypeEnum.Margin) { errCode = broker.PlaceEquityMarginDeliveryFBSOrder(stockCode, quantity, price, orderPriceType, orderDirection, orderType, exchange, out orderRef); } else if (holdingType == OrderPositionTypeEnum.OpenPendingDelivery) // only square off sell order { errCode = broker.PlaceEquityMarginSquareOffOrder(stockCode, availableQty, quantity, price, orderPriceType, orderDirection, orderType, settlementNumber, exchange, out orderRef); } var orderTypeStr = orderType == EquityOrderType.DELIVERY ? ("CASH " + holdingType) : "MARGIN"; Trace(string.Format(orderTraceFormat, stockCode, orderDirection, quantity, price, orderTypeStr, errCode, orderPriceType, settlementNumber)); if (errCode == BrokerErrorCode.Success && orderDirection == OrderDirection.BUY) { todayBuyOrderCount++; if (todayBuyOrderCount >= maxBuyOrdersAllowedInADay) { Trace(string.Format("Buy order count reached is: {0}. Max buy orders allowed: {1}", todayBuyOrderCount, maxBuyOrdersAllowedInADay)); } } return(errCode); }
public EquityOrder(String StockCode, int Quantity, String Price, OrderPriceType orderPriceType, OrderDirection orderDirection, Exchange exchange, EquityOrderType eqOrderType, String stopLossPrice, String limitPrice) { this.StockCode = StockCode; this.Quantity = Quantity; this.Price = Price; this.OrderPriceType = orderPriceType; this.OrderDirection = orderDirection; this.Exchange = exchange; this.EqOrderType = eqOrderType; this.StopLossPrice = stopLossPrice; this.LimitPrice = limitPrice; }
public BrokerErrorCode PlaceEquityOrder(string stockCode, int quantity, string price, OrderPriceType orderPriceType, OrderDirection orderDirection, EquityOrderType orderType, Exchange exchange, out string orderRef) { var errCode = broker.PlaceEquityMarginDeliveryFBSOrder(stockCode, quantity, price, orderPriceType, orderDirection, orderType, exchange, out orderRef); Trace(string.Format(orderTraceFormat, stockCode, orderDirection, quantity, price, orderType == EquityOrderType.DELIVERY ? "CASH" : "MARGIN", errCode, orderPriceType)); if (orderDirection == OrderDirection.BUY) { buyOrderCount++; if (buyOrderCount >= maxBuyOrders) { Trace(string.Format("Buy order count reached is: {0}. Max buy orders allowed: {1}", buyOrderCount, maxBuyOrders)); } } return(errCode); }
// place margin or delivery order public BrokerErrorCode PlaceEquityMarginDeliveryFBSOrder(string stockCode, int quantity, string price, OrderPriceType orderPriceType, OrderDirection orderDirection, EquityOrderType orderType, Exchange exchange, out string orderRef) { orderRef = ""; // Login If needed BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false); if (errorCode != BrokerErrorCode.Success) { return(errorCode); } string FML_ORD_ORDR_FLW_value = orderDirection == OrderDirection.BUY ? "B" : "S"; string FML_ORD_TYP_value = null, FML_ORD_LMT_RT_value = String.Empty; if (orderPriceType == OrderPriceType.MARKET) { FML_ORD_TYP_value = "M"; } else if (orderPriceType == OrderPriceType.LIMIT) { FML_ORD_TYP_value = "L"; FML_ORD_LMT_RT_value = price; } string FML_ORD_TRD_DT_value = null; string squareOffMode = orderDirection == OrderDirection.SELL ? "S" : "M"; string FML_ORD_XCHNG_CD_value = null; if (exchange == Exchange.BSE) { FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_BSE_value; FML_ORD_XCHNG_CD_value = "BSE"; } else if (exchange == Exchange.NSE) { FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_NSE_value; FML_ORD_XCHNG_CD_value = "NSE"; } string prdctType = orderType == EquityOrderType.DELIVERY ? "C" : "M"; string query = "&FML_SQ_FLAG=" + (orderType == EquityOrderType.MARGIN ? squareOffMode : "") + //Squareoff mode: M (for client) S (for broker), for BSE only S "&ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value + "&FML_STCK_CD=" + stockCode + "&FML_QTY=" + quantity.ToString() + "&FML_ORD_DSCLSD_QTY=" + "&FML_POINT_TYPE=T" + ">CDate7=" + GTCDate7 + ">CDate=" + GTCDate + ">CDateHidden7=" + GTCDateHidden7 + "&FML_ORD_TYP=" + FML_ORD_TYP_value + "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value + "&FML_GMS_CSH_PRDCT_PRCNTG=" + "&FML_ORD_STP_LSS=" + "&FML_TRADING_PASSWD=" + "&Submit=Buy+Now" + "&FML_ORD_TRD_DT_BSE=" + FML_ORD_TRD_DT_BSE_value + "&FML_ORD_TRD_DT_NSE=" + FML_ORD_TRD_DT_NSE_value + "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value + "&NSEStatus=" + NSEStatus + "&BSEStatus=" + BSEStatus + "&FML_PRCNTG_CHECK=" + FML_PRCNTG_CHECK + "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_value + "&FML_XCHNG_ST=" + NSEStatus + // O or C (open or closed) "&NicValue=" + "&FML_LAS=" + "&FML_ACCOUNT=" + "&FML_URQ_USR_RD_FLG=" + "&FML_ORD_PRDCT_TYP=" + prdctType + "&FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value + "&pgname=eqfastbuy&ismethodcall=1&mthname=DoFinalSubmit"; string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_EQT_FASTBUYSELL, query, URL_ICICI_REFERRER, mCookieContainer, out errorCode); if (errorCode.Equals(BrokerErrorCode.Success)) { errorCode = GetEQTOrderPlacementCode(orderPlacePageData); if (BrokerErrorCode.Success == errorCode) { orderRef = ExtractOrderReferenceNumber(orderPlacePageData); } } return(errorCode); }
public BrokerErrorCode PlaceEquityOrder( ref OrderUpdateEventArgs latestOrderUpdatedInfo, AutoResetEvent orderUpdatedEvent, string exchange, string stockCode, OrderDirection orderDirection, OrderPriceType orderPriceType, int quantity, EquityOrderType orderType, double price, out string orderId, out OrderStatus orderStatus) { //lock (lockSingleThreadedUpstoxCall) { BrokerErrorCode errorCode = BrokerErrorCode.Unknown; orderStatus = OrderStatus.UNKNOWN; orderId = ""; if (quantity == 0) { Trace("Not placing order as quantity is 0"); Trace(string.Format("Not placing order: {0} {1} {2} {3}@{4} {5}, as quantity is 0", orderType, stockCode, orderDirection, quantity, price, orderPriceType)); return(errorCode); } if (price == 0 && orderPriceType == OrderPriceType.LIMIT) { Trace(string.Format("Not placing order: {0} {1} {2} {3}@{4} {5}, as price is 0 for limit order", orderType, stockCode, orderDirection, quantity, price, orderPriceType)); return(errorCode); } var transType = orderDirection == OrderDirection.BUY ? "B" : "S"; var ordType = orderPriceType == OrderPriceType.LIMIT ? "L" : "M"; var prodType = orderType == EquityOrderType.DELIVERY ? "D" : "I"; try { orderId = upstox.PlaceSimpleOrder(exchange, stockCode, transType, ordType, quantity, prodType, price); Thread.Sleep(1000); // let the order status update at server errorCode = GetOrderStatus(orderId, stockCode, out orderStatus); mOrderIds[stockCode].Add(orderId); // For unsuccessful placeorder dont send orderId if (orderStatus == OrderStatus.EXPIRED || orderStatus == OrderStatus.CANCELLED || orderStatus == OrderStatus.NOTFOUND || orderStatus == OrderStatus.REJECTED || orderStatus == OrderStatus.UNKNOWN) { orderId = ""; } } catch (Exception ex) { Trace(string.Format(genericErrorLogFormat, stockCode, GeneralUtils.GetCurrentMethod(), ex.Message, ex.StackTrace)); // wait for orderupdate event signal var orderUpdateWait = orderUpdatedEvent.WaitOne(20 * 1000); lock (lockSingleThreadedUpstoxCall) { if (orderUpdateWait) { if (latestOrderUpdatedInfo != null) { // match the order if (latestOrderUpdatedInfo.Price == price && latestOrderUpdatedInfo.Quantity == quantity && latestOrderUpdatedInfo.Product == prodType && transType == latestOrderUpdatedInfo.TransType) { orderStatus = ParseOrderStatus(latestOrderUpdatedInfo.Status); orderId = latestOrderUpdatedInfo.OrderId; if (!string.IsNullOrEmpty(orderId) && !mOrderIds[stockCode].Contains(orderId)) { mOrderIds[stockCode].Add(orderId); } Trace(string.Format("{0} PlaceSimpleOrder Reconciliation completed. ErrCode={1}, OrderStatus={2}, OrderId={3}", stockCode, errorCode, orderStatus, orderId)); } else { Trace(string.Format("{0} PlaceSimpleOrder Reconciliation failed OrderNotMatched. ErrCode={1}, OrderStatus={2}, OrderId={2}", stockCode, errorCode, orderStatus, orderId)); } } else { Trace(string.Format("{0} PlaceSimpleOrder LatestOrderUpdateInfo is null . ErrCode={1}, OrderStatus={2}, OrderId={3}", stockCode, errorCode, orderStatus, orderId)); } } else { Trace(string.Format("{0} PlaceSimpleOrder Reconciliation failed NoOrderUpdate. ErrCode={1}, OrderStatus={2}, OrderId={2}", stockCode, errorCode, orderStatus, orderId)); } } } return(errorCode); } }
/// <summary> /// создать сделку /// </summary> public Position CreatePosition(string botName, Side direction, decimal priceOrder, int volume, OrderPriceType priceType, TimeSpan timeLife, Security security, Portfolio portfolio) { Position newDeal = new Position(); newDeal.Number = NumberGen.GetNumberDeal(); newDeal.Direction = direction; newDeal.State = PositionStateType.Opening; newDeal.AddNewOpenOrder(CreateOrder(direction, priceOrder, volume, priceType, timeLife)); newDeal.NameBot = botName; newDeal.Lots = security.Lot; newDeal.PriceStepCost = security.PriceStepCost; newDeal.PriceStep = security.PriceStep; newDeal.PortfolioValueOnOpenPosition = portfolio.ValueCurrent; return(newDeal); }
public override int GetHashCode() { int hash = 1; if (BrokerId.Length != 0) { hash ^= BrokerId.GetHashCode(); } if (InvestorId.Length != 0) { hash ^= InvestorId.GetHashCode(); } if (UserId.Length != 0) { hash ^= UserId.GetHashCode(); } if (InstrumentId.Length != 0) { hash ^= InstrumentId.GetHashCode(); } if (ExchangeId.Length != 0) { hash ^= ExchangeId.GetHashCode(); } if (OrderPriceType != 0) { hash ^= OrderPriceType.GetHashCode(); } if (Direction != 0) { hash ^= Direction.GetHashCode(); } if (CombOffsetFlag != 0) { hash ^= CombOffsetFlag.GetHashCode(); } if (CombHedgeFlag != 0) { hash ^= CombHedgeFlag.GetHashCode(); } if (LimitPrice != 0D) { hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(LimitPrice); } if (VolumeTotalOriginal != 0) { hash ^= VolumeTotalOriginal.GetHashCode(); } if (TimeCondition != 0) { hash ^= TimeCondition.GetHashCode(); } if (VolumeCondition != 0) { hash ^= VolumeCondition.GetHashCode(); } if (MinVolume != 0) { hash ^= MinVolume.GetHashCode(); } if (ContigentCondition != 0) { hash ^= ContigentCondition.GetHashCode(); } if (StopPrice != 0D) { hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(StopPrice); } if (ForceCloseReason != 0) { hash ^= ForceCloseReason.GetHashCode(); } if (IsAutoSuspend != 0) { hash ^= IsAutoSuspend.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public BrokerErrorCode ModifyEquityOrder( ref OrderUpdateEventArgs latestOrderUpdatedInfo, AutoResetEvent orderUpdatedEvent, string stockCode, string orderId, OrderPriceType orderPriceType, int quantity, double price, out OrderStatus orderStatus) { //lock (lockSingleThreadedUpstoxCall) { BrokerErrorCode errorCode = BrokerErrorCode.Unknown; orderStatus = OrderStatus.UNKNOWN; var ordType = orderPriceType == OrderPriceType.LIMIT ? "L" : "M"; try { upstox.ModifySimpleOrder(orderId, ordType, quantity, price, quantity); Thread.Sleep(1000); // let the order status update at server errorCode = GetOrderStatus(orderId, stockCode, out orderStatus); if (orderStatus == OrderStatus.EXPIRED || orderStatus == OrderStatus.CANCELLED || orderStatus == OrderStatus.NOTFOUND || orderStatus == OrderStatus.REJECTED || orderStatus == OrderStatus.UNKNOWN) { Trace("ModifyOrder failed with status: " + orderStatus); } } catch (Exception ex) { Trace(string.Format(genericErrorLogFormat, stockCode, GeneralUtils.GetCurrentMethod(), ex.Message, ex.StackTrace)); // wait for orderupdate event signal var orderUpdateWait = orderUpdatedEvent.WaitOne(20 * 1000); lock (lockSingleThreadedUpstoxCall) { if (orderUpdateWait) { if (latestOrderUpdatedInfo != null) { // match the order if (latestOrderUpdatedInfo.OrderId == orderId) { orderStatus = ParseOrderStatus(latestOrderUpdatedInfo.Status); Trace(string.Format("{0} ModifySimpleOrder Reconciliation completed. ErrCode={1}, OrderStatus={2}, OrderId={3}", stockCode, errorCode, orderStatus, orderId)); } else { Trace(string.Format("{0} ModifySimpleOrder Reconciliation failed OrderNotMatched. ErrCode={1}, OrderStatus={2}, OrderId={2}", stockCode, errorCode, orderStatus, orderId)); } } else { Trace(string.Format("{0} ModifySimpleOrder LatestOrderUpdateInfo is null . ErrCode={1}, OrderStatus={2}, OrderId={3}", stockCode, errorCode, orderStatus, orderId)); } } else { Trace(string.Format("{0} ModifySimpleOrder Reconciliation failed NoOrderUpdate. ErrCode={1}, OrderStatus={2}, OrderId={2}", stockCode, errorCode, orderStatus, orderId)); } } } return(errorCode); } }
/// <summary> /// OrderPriceType枚举型转为TThostFtdcOrderPriceTypeType枚举型 /// </summary> /// <param name="opt">OrderPriceType枚举型</param> /// <returns></returns> public static TThostFtdcOrderPriceTypeType OrderPriceType_To_TThostFtdcOrderPriceTypeType(OrderPriceType opt) { TThostFtdcOrderPriceTypeType tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice; switch (opt) { case OrderPriceType.AnyPrice: break; case OrderPriceType.LimitPrice: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LimitPrice; break; case OrderPriceType.BestPrice: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_BestPrice; break; case OrderPriceType.LastPrice: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LastPrice; break; case OrderPriceType.LastPricePlusOneTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LastPricePlusOneTicks; break; case OrderPriceType.LastPricePlusTwoTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LastPricePlusTwoTicks; break; case OrderPriceType.LastPricePlusThreeTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_LastPricePlusThreeTicks; break; case OrderPriceType.AskPrice1: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AskPrice1; break; case OrderPriceType.AskPrice1PlusOneTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AskPrice1PlusOneTicks; break; case OrderPriceType.AskPrice1PlusTwoTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AskPrice1PlusTwoTicks; break; case OrderPriceType.AskPrice1PlusThreeTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AskPrice1PlusThreeTicks; break; case OrderPriceType.BidPrice1: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_BidPrice1; break; case OrderPriceType.BidPrice1PlusOneTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_BidPrice1PlusOneTicks; break; case OrderPriceType.BidPrice1PlusTwoTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_BidPrice1PlusTwoTicks; break; case OrderPriceType.BidPrice1PlusThreeTicks: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_BidPrice1PlusThreeTicks; break; case OrderPriceType.FiveLevelPrice: tfoptt = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_FiveLevelPrice; break; default: break; } return(tfoptt); }
// place margin pending delivery square off order public BrokerErrorCode PlaceEquityMarginSquareOffOrder(string stockCode, int quantity, string price, OrderPriceType orderPriceType, OrderDirection orderDirection, EquityOrderType orderType, Exchange exchange, out string orderRef) { orderRef = ""; // Login If needed BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false); if (errorCode != BrokerErrorCode.Success) { return(errorCode); } string FML_ORD_ORDR_FLW_value = orderDirection == OrderDirection.BUY ? "B" : "S"; string FML_XCHNG_SGMNT_CD = ""; string FML_ORD_TYP_value = null, FML_ORD_LMT_RT_value = String.Empty; if (orderPriceType == OrderPriceType.MARKET) { FML_ORD_TYP_value = "M"; } else if (orderPriceType == OrderPriceType.LIMIT) { FML_ORD_TYP_value = "L"; FML_ORD_LMT_RT_value = price; } string FML_ORD_TRD_DT_value = null; string squareOffMode = orderDirection == OrderDirection.SELL ? "S" : "M"; string FML_ORD_XCHNG_CD_value = null; if (exchange == Exchange.BSE) { FML_XCHNG_SGMNT_CD = "B"; FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_BSE_value; FML_ORD_XCHNG_CD_value = "BSE"; } else if (exchange == Exchange.NSE) { FML_XCHNG_SGMNT_CD = "N"; FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_NSE_value; FML_ORD_XCHNG_CD_value = "NSE"; } string prdctType = orderType == EquityOrderType.DELIVERY ? "C" : "M"; string query = "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value + "&FML_STCK_CD=" + stockCode + "&FML_QTY=" + quantity.ToString() + "&FML_XCHNG_SGMNT_CD=" + FML_XCHNG_SGMNT_CD + "&FML_STTLMNT_NMBR=" + "&AvgPrc=" + "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_NSE_value + "&FML_XCHNG_ST=" + NSEStatus + "&NicValue=" + "&m_IntPass=1" + "&FML_URQ_USR_RD_FLG=" + "&FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value + "&FML_ORD_DSCLSD_QTY=" + "&FML_SQROFF=" + quantity.ToString() + "&FML_POINT_TYPE=T" + "&FML_ORD_TYP=" + FML_ORD_TYP_value + "&FML_LM_RT=" + FML_ORD_LMT_RT_value + "&FML_GMS_CSH_PRDCT_PRCNTG=" + "&FML_ORD_STP_LSS=" + "&Submit1=Square Off" + "&Submit2=Clear" + "&FML_ORD_XCHNG_SGMNT_STTLMNT=" + "&FML_QUOTE=" + "&FML_QUOTE_TIME=" + "&FML_TRDNG_PSSWRD_FLG=N" + "&FML_RT=" + "&FML_ISIN_NMBR=" + "&FML_STK_STCK_NM=" + "&FML_TM=" + "&FML_QTY_OTH=" + quantity.ToString() + "&pgname=EquityPendingForDeliverySquareOff" + "&ismethodcall=1" + "&mthname=ValidateFormData"; string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_BASE_ACTION, query, URL_ICICI_REFERRER, mCookieContainer, out errorCode); if (errorCode.Equals(BrokerErrorCode.Success)) { errorCode = GetEQTOrderPlacementCode(orderPlacePageData); if (BrokerErrorCode.Success == errorCode) { orderRef = ExtractOrderReferenceNumberMarginSqOffOrder(orderPlacePageData); } } return(errorCode); }
public async Task <JToken> PlaceOrderAsync(string instrument, Side side, decimal price, OrderPriceType orderType, decimal amount, bool reduceOnly = false) { var path = $"api/orders"; var body = $"{{\"market\": \"{instrument}\"," + $"\"side\": \"{side.ToString().ToLower()}\"," + $"\"price\": {price.ToString(CultureInfo.InvariantCulture)}," + $"\"type\": \"{orderType.ToString().ToLower()}\"," + $"\"size\": {amount.ToString(CultureInfo.InvariantCulture)}," + $"\"reduceOnly\": {reduceOnly.ToString().ToLower()}}}"; var sign = GenerateSignature(HttpMethod.Post, "/api/orders", body); var result = await CallAsyncSign(HttpMethod.Post, path, sign, body); return(ParseResponce(result)); }
public OrderPrice(OrderPriceType type, decimal amount) { Type = type; Amount = amount; }
// place deliver order public BrokerErrorCode PlaceEquityMarginDeliveryFBSOrder(string stockCode, int quantity, string price, OrderPriceType orderPriceType, OrderDirection orderDirection, EquityOrderType orderType, Exchange exchange) { // Login If needed BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false); if (errorCode != BrokerErrorCode.Success) { return(errorCode); } string FML_ORD_ORDR_FLW_value = null; if (orderDirection == OrderDirection.BUY) { FML_ORD_ORDR_FLW_value = "B"; } else if (orderDirection == OrderDirection.SELL) { FML_ORD_ORDR_FLW_value = "S"; } string FML_ORD_TYP_value = null, FML_ORD_LMT_RT_value = String.Empty; if (orderPriceType == OrderPriceType.MARKET) { FML_ORD_TYP_value = "M"; } else if (orderPriceType == OrderPriceType.LIMIT) { FML_ORD_TYP_value = "L"; FML_ORD_LMT_RT_value = price; } string FML_ORD_TRD_DT_value = null; string squareOffMode = "S"; string FML_ORD_XCHNG_CD_value = null; if (exchange == Exchange.BSE) { FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_BSE_value; FML_ORD_XCHNG_CD_value = "BSE"; squareOffMode = "S"; } else if (exchange == Exchange.NSE) { FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_NSE_value; FML_ORD_XCHNG_CD_value = "NSE"; squareOffMode = "M"; } string prdctType = orderType == EquityOrderType.DELIVERY ? "CASH" : "MARGIN"; string query = "FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value + "&FML_ACCOUNT=" + FML_ACCOUNT_value + "&TEMP=" + FML_ORD_XCHNG_CD_value + "&FML_ORD_PRDCT_TYP=" + prdctType + (orderType == EquityOrderType.MARGIN ? "&FML_SQ_FLAG=" + squareOffMode : "") + //Squareoff mode: M (for client) S (for broker), for BSE only S "&FML_STCK_CD=" + stockCode + "&FML_QTY=" + quantity.ToString() + "&FML_DOTNET_FLG=Y&FML_URL_FLG=http%3A%2F%2Fgetquote.icicidirect.com%2Ftrading%2Fequity%2Ftrading_stock_quote.asp " + "&FML_ORD_TYP=" + FML_ORD_TYP_value + "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value + "&FML_ORD_DSCLSD_QTY=&FML_ORD_STP_LSS=" + "&FML_ORD_TRD_DT_BSE=" + FML_ORD_TRD_DT_BSE_value + "&FML_ORD_TRD_DT_NSE=" + FML_ORD_TRD_DT_NSE_value + "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_value + "&FML_PRODUCT_INDEX=0" + "&FML_ORD_PRD_HIDDEN=" + prdctType + "&FML_ORD_CLM_MTCH_ACCNT=" + "&FML_TRADING_LIMIT_NSE=" + FML_TRADING_LIMIT_NSE_value + "&FML_TRADING_LIMIT_BSE=" + FML_TRADING_LIMIT_BSE_value + "&FML_ORD_DP_CLNT_ID=&FML_ORD_DP_ID=&FML_TRN_PRDT_TYP=" + "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value + "&FML_ORD_XCHNG_CD_CHECK=" + (exchange == Exchange.BSE ? "NSE" : "") + "&FML_PRCNTG_CHECK=3.0&FML_ARRAY_BOUND=1&FML_ARRAY_ELEMENT=&NicValue=&BrowserBack_Xchang=NSE&PWD_ENABLED=N&FML_LAS=Y" + "&m_FML_AC_ACTIVATED_FROM=BSE&m_FML_USR_ZIP_CD=B3&m_FML_AC_ACTIVATED_FROM=NSE&m_FML_USR_ZIP_CD=N9"; string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_EQT_FBS_CASHMARGIN_ORDER, query, URL_ICICI_REFERRER, mCookieContainer, out errorCode); if (errorCode.Equals(BrokerErrorCode.Success)) { errorCode = GetEQTOrderPlacementCode(orderPlacePageData, EquityOrderType.DELIVERY); if (BrokerErrorCode.Success == errorCode) { // ********** Get exchange reference number (primary key for an order) *********** // add the record to DB GetOrderConfirmationData(orderPlacePageData, orderType); } } return(errorCode); }
// внутренние функции управления позицией // internal position management functions private void CloseDeal(Position position, OrderPriceType priceType, decimal price, TimeSpan lifeTime, bool isStopOrProfit) { try { if (position == null) { return; } position.ProfitOrderIsActiv = false; position.StopOrderIsActiv = false; for (int i = 0; position.CloseOrders != null && i < position.CloseOrders.Count; i++) { if (position.CloseOrders[i].State == OrderStateType.Activ && position.CloseOrders[i].TypeOrder != OrderPriceType.LimitStop && position.CloseOrders[i].TypeOrder != OrderPriceType.MarketStop ) { _connector.OrderCancel(position.CloseOrders[i]); } } for (int i = 0; position.OpenOrders != null && i < position.OpenOrders.Count; i++) { if (position.OpenOrders[i].State == OrderStateType.Activ && position.OpenOrders[i].TypeOrder != OrderPriceType.LimitStop && position.OpenOrders[i].TypeOrder != OrderPriceType.MarketStop ) { _connector.OrderCancel(position.OpenOrders[i]); } } if (Securiti == null) { return; } Side sideCloseOrder = Side.Buy; if (position.Direction == Side.Buy) { sideCloseOrder = Side.Sell; } price = RoundPrice(price, Securiti, sideCloseOrder); if (position.State == PositionStateType.Done && position.OpenVolume == 0) { return; } position.State = PositionStateType.Closing; Order closeOrder = _dealCreator.CreateCloseOrderForDeal(position, price, priceType, lifeTime, StartProgram); if (closeOrder == null) { if (position.OpenVolume == 0) { position.State = PositionStateType.OpeningFail; } return; } if (isStopOrProfit) { closeOrder.IsStopOrProfit = true; } position.AddNewCloseOrder(closeOrder); _connector.OrderExecute(closeOrder); } catch (Exception error) { SetNewLogMessage(error.ToString(), LogMessageType.Error); } }