internal static void LogOrder(LoggingConfig config, string orderName, OrderSide orderSide, double qty, double price, int retryCount) { Console.WriteLine("---------------------------"); string message = string.Format("{0} - {1} {2} @ {3} for {4:C}", orderName, orderSide, qty, price, qty * price); Console.WriteLine(string.Format(ORDER_STRING, DateTime.Now, config.Instrument.Symbol, message, retryCount)); Console.WriteLine("---------------------------"); }
public NewOrderResponse ExecuteOrder(OrderSymbol symbol, decimal amount, decimal price, OrderExchange exchange, OrderSide side, OrderType type) { NewOrderRequest req = new NewOrderRequest(Nonce, symbol, amount, price, exchange, side, type); string response = SendRequest(req,"POST"); NewOrderResponse resp = NewOrderResponse.FromJSON(response); return resp; }
protected string GetAutoPlacedOrderName(OrderType orderType, OrderSide orderSide, string info, string instrument, int retrials, string ibAccountNumber) { if (string.IsNullOrEmpty(info)) return string.Format("ACCT: {4} -- {0}: {1} order for {2} [#{3}]", orderType, orderSide, instrument, retrials, ibAccountNumber); else return string.Format("ACCT: {5} -- {0}: {1} ({2}) order {3} [#{4}]", orderType, orderSide, info, instrument, retrials, ibAccountNumber); }
public double GetMatchPrice(Strategy strategy, OrderSide side) { Quote quote = strategy.Quote; Trade trade = strategy.Trade; Bar bar = strategy.Bar; if (quote != null) { if (side == OrderSide.Buy) { if (quote.Ask != 0) return quote.Ask; } else { if (quote.Bid != 0) return quote.Bid; } } if (trade != null) if (trade.Price != 0) return trade.Price; if (bar != null) { if (bar.Close != 0) return bar.Close; if (bar.Open != 0) return bar.Open; } return 0; }
public int GetKeyByPrice(double price, OrderSide Side) { price = Math.Min(price, UpperLimitPrice); price = Math.Max(price, LowerLimitPrice); int index = (int)((Side == OrderSide.Buy) ? Math.Ceiling(price / TickSize) : Math.Floor(price / TickSize)); return index; }
internal static Side Convert(OrderSide side) { switch (side) { case OrderSide.Buy: return Side.Buy; case OrderSide.Sell: return Side.Sell; default: throw new ArgumentException(string.Format("Unsupported OrderSide - {0}", side)); } }
public Fill(DateTime dateTime, Order order, Instrument instrument, byte currencyId, OrderSide side, double qty, double price, string text = "") { DateTime = dateTime; Order = order; Instrument = instrument; OrderId = order.Id; InstrumentId = instrument.Id; CurrencyId = currencyId; Side = side; Qty = qty; Price = price; Text = text; }
private void ReAdjustTheNumberOfRetrialsConsumed(double lastPrice, OrderSide orderSide) { double originalOpeningPrice = EffectiveOriginalOpeningPriceAtStartOfStrategy; if (lastPrice <= 0) { LoggingUtility.WriteWarn(LoggingConfig, string.Format("Cannot calculate stop price condition for LAST price {0:c}", lastPrice)); return; } bool needToReadjustRetryCount = true; if (orderSide == OrderSide.Buy) { needToReadjustRetryCount = lastPrice > originalOpeningPrice; } else { needToReadjustRetryCount = lastPrice < originalOpeningPrice; } if (!needToReadjustRetryCount) return; double absPriceDiff=0; double atrPriceDiff=0; absPriceDiff = Math.Abs(lastPrice - originalOpeningPrice); if (EffectiveAtrPrice > 0) atrPriceDiff = absPriceDiff/EffectiveAtrPrice; // Retrial consumed has already been incremented by 1. So substract 1 from overall count calculated int retriesConsumed = Convert.ToInt32(atrPriceDiff/AdverseMovementInPriceAtrThreshold) - 1; if (retriesConsumed > 0 && EffectiveOrderRetriesConsumed < retriesConsumed) { EffectiveOrderRetriesConsumed = retriesConsumed; LoggingUtility.WriteInfo( LoggingConfig, string.Format( "Incrementing the EffectiveOrderRetriesConsumed to {0} because the price {1:c} has moved {2} ATR in adverse direction from the original opening price of {3:c}", retriesConsumed, lastPrice, atrPriceDiff, originalOpeningPrice)); if (EffectiveOrderRetriesConsumed >= MaximumRetries) EffectiveOrderRetriesConsumed = MaximumRetries; } }
public QuantityTradeLeg(int idx, Instrument instrument, OrderSide orderSide, double qty) : base(idx, instrument, orderSide) { this.QuantityToFill = qty; this.LegName = string.Format("Q{0}.{1}.{2}.{3}", this.Index, this.Instrument.Symbol.ToUpper(), this.OrderSide, this.QuantityToFill); Log.WriteInfoLog(LegName, this.Instrument, string.Format("Quantity leg generated to {0} {1:N2} units", this.OrderSide.ToString().ToUpper(), this.QuantityToFill)); }
public Order(IExecutionProvider provider, Instrument instrument, OrderType type, OrderSide side, double qty, double price = 0.0, double stopPx = 0.0, TimeInForce timeInForce = TimeInForce.Day, string text = "") : this() { this.provider = provider; this.instrument = instrument; this.type = type; this.side = side; this.qty = qty; this.price = price; this.stopPx = stopPx; this.timeInForce = timeInForce; this.text = text; this.portfolio = null; }
public AmountTradeLeg(int idx, Instrument instrument, OrderSide orderSide, double amt) : base(idx, instrument, orderSide) { this.AmountToFill = amt; this.LegName = string.Format("A{0}.{1}.{2}.{3:c}", this.Index, this.Instrument.Symbol.ToUpper(), this.OrderSide, this.AmountToFill); Log.WriteInfoLog(LegName, this.Instrument, string.Format("Amount leg generated to {0} {1:c2}", this.OrderSide.ToString().ToUpper(), this.AmountToFill)); }
public EnumOpenClose CanClose(OrderSide Side, double qty) { bool bCanClose = false; if (Side == OrderSide.Buy) { bCanClose = Short.CanClose(qty); } else { bCanClose = Long.CanClose(qty); } if (bCanClose) return EnumOpenClose.CLOSE; return EnumOpenClose.OPEN; }
/// <summary> /// /// </summary> /// <param name="price"></param> /// <param name="orderType"></param> /// <returns></returns> protected double GetSlippageAdjustedPrice(double price, OrderSide orderType) { double slippageAmount = price * NextBarSlippagePercentage / 100; double targetPrice = price; if (orderType == OrderSide.Buy) { targetPrice = targetPrice + slippageAmount; } else { targetPrice = targetPrice - slippageAmount; } return targetPrice; }
public double Cancel(OrderSide Side) { lock (this) { double qty; if (Side == OrderSide.Buy) { qty = Buy.Cancel(); } else { qty = Sell.Cancel(); } return qty; } }
internal bool IsEntryStopPriceMet(double lastPrice, double stopPrice, OrderSide orderSide) { bool stopMet = false; if (orderSide == OrderSide.Buy) stopMet = lastPrice >= stopPrice; else stopMet = lastPrice <= stopPrice; if (stopMet) LoggingUtility.WriteInfo( logConfig, string.Format( "Stop price of {0:c} was met on {1} side by last close price of {2:c}", stopPrice, orderSide, lastPrice)); return stopMet; }
// These converters convert OQ enums to IB enums and back // all follow the same pattern // if a conversion is not possible they return false. // the caller is expected to create an error message and ignore // the class containing the enum which is not convertible public static bool ActionSideToOrderSide(ActionSide action, out OrderSide side) { side = OrderSide.Buy; switch (action) { case ActionSide.Buy: side = OrderSide.Buy; break; case ActionSide.Sell: side = OrderSide.Sell; break; case ActionSide.SShort: side = OrderSide.Sell; break; case ActionSide.Undefined: default: return false; } return true; }
internal bool IsStopPriceMet(double lastPrice, double stopPrice, OrderSide orderSide, StopPriceCalculationStrategy stopStrategy, string info) { bool stopMet = false; if (lastPrice <= 0) { LoggingUtility.WriteWarn(logConfig, string.Format("Cannot calculate stop price condition for LAST price {0:c}", lastPrice)); return stopMet; } if (stopPrice <= 0) { LoggingUtility.WriteVerbose(logConfig, string.Format("Cannot calculate stop price condition for STOP price {0:c}", stopPrice)); return stopMet; } if (orderSide == OrderSide.Buy) stopMet = lastPrice > stopPrice; else stopMet = lastPrice < stopPrice; if (stopMet) LoggingUtility.WriteInfo( logConfig, string.Format( "[{4}] Stop price of {0:c} was met on {1} side by last close price of {2:c} based on {3} strategy", stopPrice, orderSide, lastPrice, stopStrategy, info)); return stopMet; }
public void SendLimitOrder(Instrument instrument, OrderSide side, double qty, double limitPrice, string text) { this.LimitOrder(instrument, side, qty, limitPrice, text).Send(); }
private async Task <OrderDto> ExecuteTakeProfitOrder(string market, int quantity, decimal price, decimal trigger, OrderSide orderSide) { var apiActionAttributes = new ApiActionAttributes <OrderPOSTRequestParams, OrderDto>("order", HttpMethods.POST); Logger.Info($"Take profit trigger at {trigger}, {orderSide} at {price}"); return(await _bitmexApiService.Execute(apiActionAttributes, new OrderPOSTRequestParams { Symbol = market, Side = Enum.GetName(typeof(OrderSide), orderSide), OrderQty = quantity, OrdType = "LimitIfTouched", StopPx = trigger, Price = price, ExecInst = "Close,LastPrice", TimeInForce = "GoodTillCancel" })); }
static public OrdersCompletedViewModel Construct(ApplicationUser loggedInUser, ApplicationUser tradeUser, string market, OrderSide side, ExchangeSettings settings, int offset, int limit) { var via = new ViaJsonRpc(settings.AccessHttpUrl); var now = DateTimeOffset.Now.ToUnixTimeSeconds(); var bidOrdersCompleted = via.OrdersCompletedQuery(tradeUser.Exchange.Id, market, 1, now, offset, limit, side); var model = new OrdersCompletedViewModel { User = loggedInUser, Market = market, MarketNice = string.Format("{0}/{1}", settings.Markets[market].AmountUnit, settings.Markets[market].PriceUnit), AssetSettings = settings.Assets, Settings = settings.Markets[market], OrdersCompleted = bidOrdersCompleted, }; return(model); }
public static Orderbook GetOrderbook(this Market market, OrderSide side) { return(side == OrderSide.Buy ? market.Bids : market.Asks); }
public static OrderPOSTRequestParams CreateLimitStopOrder(string symbol, int quantity, decimal stopPrice, decimal price, OrderSide side) { return(new OrderPOSTRequestParams { Symbol = symbol, Side = Enum.GetName(typeof(OrderSide), side), OrderQty = quantity, OrdType = Enum.GetName(typeof(OrderType), OrderType.Stop), StopPx = stopPrice, Price = price, ExecInst = "ReduceOnly,LastPrice", }); }
public IEnumerable<OrderBookDetail> GetDetails(OrderSide.Simplified side, int count) { if (side == OrderSide.Simplified.Sell) return Sides[(int) side].Values.OrderBy(o => o.Price).Take(count).Reverse(); else return Sides[(int) side].Values.OrderByDescending(o => o.Price).Take(count); }
public ExchangeEthOrder(ExchangePricesEventArgs arg, Instrument ins, OrderSide type) : base(arg, ins, type) { }
public NewOrderRequest(string nonce, OrderSymbol symbol, decimal amount, decimal price, OrderExchange exchange, OrderSide side, OrderType type) { this.symbol = EnumHelper.EnumToStr(symbol); this.amount = amount.ToString(CultureInfo.InvariantCulture); this.price = price.ToString(CultureInfo.InvariantCulture); this.exchange = EnumHelper.EnumToStr(exchange); this.side = EnumHelper.EnumToStr(side); this.type = EnumHelper.EnumToStr(type); this.nonce = nonce; this.request = "/v1/order/new"; }
private void ScalperTask(XSymbol xs, OrderSide initSide, decimal initPrice, decimal amount, decimal scalp) { Console.WriteLine("\n===== Starting Scalper {0} init_price:{1:0.00000000} amount:{2} scalp:{3:0.00000000} =====", xs, initPrice, amount, scalp); var api = m_api[xs.Exchange]; string strategyId = "scalper"; ExchangeOrderResult working; if (initSide == OrderSide.Sell) { working = m_om.PlaceOrder(api, xs.Symbol, initSide, initPrice + scalp, amount, strategyId); } else { working = m_om.PlaceOrder(api, xs.Symbol, initSide, initPrice - scalp, amount, strategyId); } Console.WriteLine("\n NEW working order >>> {0} ", working.ToStr()); int count = 0; while (true) { Thread.Sleep(m_testOnly ? 25000 : 15000); var t = api.GetTicker(xs.Symbol); //if (working.Result == ExchangeAPIOrderResult.Filled) // If our working order has been filled if (m_orders.Where(o => o.OrderId == working.OrderId).Count() == 0) { var buySell = working.IsBuy ? "BOT" : "SOLD"; var prowlEvt = string.Format("Fill {0} {1} {2:0.00000000}", working.Symbol, buySell, working.Price); if (working.IsBuy) { working = m_om.PlaceOrder(api, xs.Symbol, OrderSide.Sell, initPrice + scalp, amount, strategyId); } else { working = m_om.PlaceOrder(api, xs.Symbol, OrderSide.Buy, initPrice - scalp, amount, strategyId); } Console.WriteLine("\n*** {0} ***\n NEW working order >>> {1}", prowlEvt, working.ToStr()); m_prowl.Send(prowlEvt, working.ToMsgStr()); } else if (Math.Abs(t.Last - initPrice) > 2 * scalp) // if price breakout of range { string dir = "up"; if (t.Last < initPrice) { dir = "down"; } if (working.Side() == initSide) { m_om.Cancel(working); } initPrice = t.Last; if (initSide == OrderSide.Sell) { working = m_om.PlaceOrder(api, xs.Symbol, initSide, initPrice + scalp, amount, strategyId); } else { working = m_om.PlaceOrder(api, xs.Symbol, initSide, initPrice - scalp, amount, strategyId); } Console.WriteLine("\n*** Price Breakout {0} {1} ***\n NEW working order >>> {2} ", xs.Symbol, dir, working.ToStr()); //m_prowl.Send(string.Format("Breakout {0} {1}", working.Symbol, dir), working.ToMsgStr()); } if (count % 4 == 0) { Console.Write("."); } //if (count % 10 == 0) Console.WriteLine("{0}", working.ToStr()); } }
public async Task <Order> CreateOrder(string exchangeId, string symbol, OrderType type, OrderSide side, float amount, float price, Dictionary <string, object> parameters = null) { return(await GetData <Order>("create_order", exchangeId, null, true, -1, true, symbol, type.ToString(), side.ToString(), amount, price, parameters)); }
public OrderbookBase GetOrderbook(int asset, OrderSide side) { return(GetMarket(asset).GetOrderbook(side)); }
public double FixPrice(double price, OrderSide side) { return(GetPriceByLevel(GetLevelByPrice(price, side))); }
public Order StopLimitOrder(Instrument instrument, OrderSide side, double qty, double limitPrice, double stopPrice) { return this.StopLimitOrder(instrument, side, qty, limitPrice, stopPrice, ""); }
public static bool OrderSideToActionSide(OrderSide orderside, out ActionSide action) { action = ActionSide.Undefined; switch (orderside) { case OrderSide.Buy: action = ActionSide.Buy; break; case OrderSide.Sell: action = ActionSide.Sell; break; default: return false; } return true; }
/// <summary> /// Places a new order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="side">The order side (buy/sell)</param> /// <param name="type">The order type</param> /// <param name="timeInForce">Lifetime of the order (GoodTillCancel/ImmediateOrCancel/FillOrKill)</param> /// <param name="quantity">The amount of the base symbol</param> /// <param name="positionSide">The position side</param> /// <param name="reduceOnly">Specify as true if the order is intended to only reduce the position</param> /// <param name="price">The price to use</param> /// <param name="newClientOrderId">Unique id for order</param> /// <param name="stopPrice">Used for stop orders</param> /// <param name="activationPrice">Used with TRAILING_STOP_MARKET orders, default as the latest price(supporting different workingType)</param> /// <param name="callbackRate">Used with TRAILING_STOP_MARKET orders</param> /// <param name="workingType">stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE"</param> /// <param name="closePosition">Close-All,used with STOP_MARKET or TAKE_PROFIT_MARKET.</param> /// <param name="orderResponseType">The response type. Default Acknowledge</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Id's for the placed order</returns> public async Task <WebCallResult <BinanceFuturesPlacedOrder> > PlaceOrderAsync( string symbol, OrderSide side, OrderType type, decimal?quantity, PositionSide?positionSide = null, TimeInForce?timeInForce = null, bool?reduceOnly = null, decimal?price = null, string?newClientOrderId = null, decimal?stopPrice = null, decimal?activationPrice = null, decimal?callbackRate = null, WorkingType?workingType = null, bool?closePosition = null, OrderResponseType?orderResponseType = null, int?receiveWindow = null, CancellationToken ct = default) { if (closePosition == true && positionSide != null) { if (positionSide == PositionSide.Short && side == OrderSide.Sell) { throw new ArgumentException("Can't close short position with order side sell"); } if (positionSide == PositionSide.Long && side == OrderSide.Buy) { throw new ArgumentException("Can't close long position with order side buy"); } } if (orderResponseType == OrderResponseType.Full) { throw new ArgumentException("OrderResponseType.Full is not supported in Futures"); } var timestampResult = await BaseClient.CheckAutoTimestamp(ct).ConfigureAwait(false); if (!timestampResult) { return(new WebCallResult <BinanceFuturesPlacedOrder>(timestampResult.ResponseStatusCode, timestampResult.ResponseHeaders, null, timestampResult.Error)); } var rulesCheck = await FuturesClient.CheckTradeRules(symbol, quantity, price, stopPrice, type, ct).ConfigureAwait(false); if (!rulesCheck.Passed) { _log.Write(LogVerbosity.Warning, rulesCheck.ErrorMessage !); return(new WebCallResult <BinanceFuturesPlacedOrder>(null, null, null, new ArgumentError(rulesCheck.ErrorMessage !))); } quantity = rulesCheck.Quantity; price = rulesCheck.Price; var parameters = new Dictionary <string, object> { { "symbol", symbol }, { "side", JsonConvert.SerializeObject(side, new OrderSideConverter(false)) }, { "type", JsonConvert.SerializeObject(type, new OrderTypeConverter(false)) }, { "timestamp", BaseClient.GetTimestamp() } }; parameters.AddOptionalParameter("quantity", quantity?.ToString(CultureInfo.InvariantCulture)); parameters.AddOptionalParameter("newClientOrderId", newClientOrderId); parameters.AddOptionalParameter("price", price?.ToString(CultureInfo.InvariantCulture)); parameters.AddOptionalParameter("timeInForce", timeInForce == null ? null : JsonConvert.SerializeObject(timeInForce, new TimeInForceConverter(false))); parameters.AddOptionalParameter("positionSide", positionSide == null ? null : JsonConvert.SerializeObject(positionSide, new PositionSideConverter(false))); parameters.AddOptionalParameter("stopPrice", stopPrice?.ToString(CultureInfo.InvariantCulture)); parameters.AddOptionalParameter("activationPrice", activationPrice?.ToString(CultureInfo.InvariantCulture)); parameters.AddOptionalParameter("callbackRate", callbackRate?.ToString(CultureInfo.InvariantCulture)); parameters.AddOptionalParameter("workingType", workingType == null ? null : JsonConvert.SerializeObject(workingType, new WorkingTypeConverter(false))); parameters.AddOptionalParameter("reduceOnly", reduceOnly?.ToString().ToLower()); parameters.AddOptionalParameter("closePosition", closePosition?.ToString().ToLower()); parameters.AddOptionalParameter("newOrderRespType", orderResponseType == null ? null : JsonConvert.SerializeObject(orderResponseType, new OrderResponseTypeConverter(false))); parameters.AddOptionalParameter("recvWindow", receiveWindow?.ToString(CultureInfo.InvariantCulture) ?? BaseClient.DefaultReceiveWindow.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)); return(await BaseClient.SendRequestInternal <BinanceFuturesPlacedOrder>(FuturesClient.GetUrl(newOrderEndpoint, Api, SignedVersion), HttpMethod.Post, ct, parameters, true).ConfigureAwait(false)); }
protected string GetAutoPlacedOrderName(OrderSide orderSide, string info, string instrument) { if (string.IsNullOrEmpty(info)) return string.Format("{0} order for {1}", orderSide, instrument); else return string.Format("{0} ({1}) order {2}", orderSide, info, instrument); }
/// <summary> /// Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. /// </summary> /// <param name="symbol">Ticker symbol.</param> /// <param name="quantity">Quantity to transaction.</param> /// <param name="price">Price of the transaction.</param> /// <param name="orderType">Order type (LIMIT-MARKET).</param> /// <param name="side">Order side (BUY-SELL).</param> /// <param name="timeInForce">Indicates how long an order will remain active before it is executed or expires.</param> /// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param> /// <returns></returns> public async Task <dynamic> PostNewOrderTest(string symbol, decimal quantity, decimal price, OrderSide side, OrderType orderType = OrderType.LIMIT, TimeInForce timeInForce = TimeInForce.GTC, decimal icebergQty = 0m, long recvWindow = 5000) { //Validates that the order is valid. ValidateOrderValue(symbol, orderType, price, quantity, icebergQty); var args = $"symbol={symbol.ToUpper()}&side={side}&type={orderType}&quantity={quantity}" + (orderType == OrderType.LIMIT ? $"&timeInForce={timeInForce}" : "") + (orderType == OrderType.LIMIT ? $"&price={price}" : "") + (icebergQty > 0m ? $"&icebergQty={icebergQty}" : "") + $"&recvWindow={recvWindow}"; var result = await _apiClient.CallAsync <dynamic>(ApiMethod.POST, EndPoints.NewOrderTest, true, args); return(result); }
public OrdersCompleted OrdersCompletedQuery(int user_id, string market, long start_time, long end_time, int offset, int limit, OrderSide side) { call_id++; var json = JsonBody(call_id, "order.finished", new object[] { user_id, market, start_time, end_time, offset, limit, side }); json = client.PostJson(json); var resp = JsonConvert.DeserializeObject <OrdersCompletedResponse>(json); resp.CheckId(call_id); if (resp.Error != null) { throw new ViaJsonException(resp.Error.Code, resp.Error.Message); } return(resp.Result); }
public AnalyticsOrderbook GetOrderbook(OrderSide side) { return(side == OrderSide.Buy ? Bids : Asks); }
/// <summary> /// Synchronized version of the <see cref="PlaceOrderAsync"/> method /// </summary> /// <returns></returns> public BinanceApiResult <BinancePlacedOrder> PlaceOrder(string symbol, OrderSide side, OrderType type, TimeInForce timeInForce, decimal quantity, decimal price, string newClientOrderId = null, decimal?stopPrice = null, decimal?icebergQty = null) => PlaceOrderAsync(symbol, side, type, timeInForce, quantity, price, newClientOrderId, stopPrice, icebergQty).Result;
public async Task <OrderResponse> LimitOrder(ProductType productId, OrderSide side, decimal size, decimal price, bool postOnly = true, Guid?clientOid = null) { var res = await m_client.OrdersService.PlaceLimitOrderAsync(side, productId, size, price, GoodTillTime.Day, postOnly, clientOid); return(res); }
public override void cycleStrategy() { if (processStrategy) { return; } else { processStrategy = true; } try { Double profitUSD = server.TradeUSD.GetValueOrDefault() * server.MinProfit.GetValueOrDefault(); switch (State) { case StrategyState.Inactive: break; case StrategyState.Active: case StrategyState.Continuous: if (Profit >= profitUSD) { State = StrategyState.MakerSend; DctLegToOrder.Clear(); goto case StrategyState.MakerSend; } break; case StrategyState.MakerSend: CurrentLeg = MakerLeg; double dUSD = server.TradeUSD.GetValueOrDefault(); OrderSide sideMaker = dctLegs[CurrentLeg].Item1; CProduct productMaker = dctLegs[CurrentLeg].Item2; Double sizeMaker = GetSize(sideMaker, productMaker); Double priceMaker = (double)(sideMaker == OrderSide.Buy ? productMaker.Bid : productMaker.Ask); dctLegs[MakerLeg].Item2.Exchange.trade(this, MakerLeg, sideMaker, productMaker, Math.Round(sizeMaker, productMaker.PrecisionSize), Math.Round(priceMaker, productMaker.PrecisionPrice)); State = StrategyState.MakerProcess; break; case StrategyState.MakerProcess: COrder order = DctLegToOrder[MakerLeg]; if (order.Status.Equals(COrder.OrderState.Filled)) { State = StrategyState.TakerSend; goto case StrategyState.TakerSend; } else if (Profit < profitUSD && order.canCancel()) { order.cancel(); State = Continuous ? StrategyState.Continuous : StrategyState.Active; DctLegToOrder.Clear(); } break; case StrategyState.TakerSend: for (int currentLeg = 1; currentLeg <= dctLegs.Count; currentLeg++) { if (!DctLegToOrder.ContainsKey(currentLeg)) { OrderSide sideTaker = dctLegs[currentLeg].Item1; CProduct productTaker = dctLegs[currentLeg].Item2; Double sizeTaker = GetSize(sideTaker, productTaker); Double priceTaker = ((Double)productTaker.Bid + (Double)productTaker.Ask) / 2.0; CurrentLeg = currentLeg; dctLegs[currentLeg].Item2.Exchange.trade(this, currentLeg, sideTaker, productTaker, Math.Round(sizeTaker, productTaker.PrecisionSize), Math.Round(priceTaker, productTaker.PrecisionPrice)); } } if (DctLegToOrder.Count >= 3) { State = StrategyState.TakerProcess; } break; case StrategyState.TakerProcess: Boolean allFilled = true; for (int currentLeg = 1; currentLeg <= dctLegs.Count; currentLeg++) { if (DctLegToOrder.ContainsKey(currentLeg)) { COrder orderTaker = DctLegToOrder[currentLeg]; if (orderTaker.Status.Equals(COrder.OrderState.Sent) || orderTaker.Status.Equals(COrder.OrderState.Cancelled)) { allFilled = false; } else if (orderTaker.canCancel()) { allFilled = false; CExchange exchange = orderTaker.Exchange; OrderSide sideTaker = orderTaker.Side; CProduct productTaker = orderTaker.Product; Double sizeTaker = orderTaker.Size; Double priceTaker = ((Double)productTaker.Bid + (Double)productTaker.Ask) / 2.0; CurrentLeg = currentLeg; orderTaker.cancel(); COrder orderCancel; DctLegToOrder.TryRemove(currentLeg, out orderCancel); exchange.trade(this, currentLeg, sideTaker, productTaker, Math.Round(sizeTaker, productTaker.PrecisionSize), Math.Round(priceTaker, productTaker.PrecisionPrice)); } } else { allFilled = false; } } if (allFilled) { if (Continuous) { State = StrategyState.Continuous; } else { State = StrategyState.Inactive; } DctLegToOrder.Clear(); } break; } } catch (Exception ex) { server.AddLog(ex.Message); } processStrategy = false; }
/// <summary> /// Create close all order request /// </summary> private static O2GRequest CreateCloseAllRequest(O2GSession session, Dictionary <string, CloseOrdersData> closeOrdersData) { O2GRequest request = null; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GValueMap batchValuemap = requestFactory.createValueMap(); batchValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); Dictionary <string, CloseOrdersData> .Enumerator enumerator = closeOrdersData.GetEnumerator(); while (enumerator.MoveNext()) { string sOfferID = enumerator.Current.Key; string sAccountID = enumerator.Current.Value.AccountID; OrderSide side = enumerator.Current.Value.Side; O2GValueMap childValuemap; switch (side) { case OrderSide.Buy: childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); batchValuemap.appendChild(childValuemap); break; case OrderSide.Sell: childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); batchValuemap.appendChild(childValuemap); break; case OrderSide.Both: childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Buy); batchValuemap.appendChild(childValuemap); childValuemap = requestFactory.createValueMap(); childValuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); childValuemap.setString(O2GRequestParamsEnum.NetQuantity, "Y"); childValuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose); childValuemap.setString(O2GRequestParamsEnum.AccountID, sAccountID); childValuemap.setString(O2GRequestParamsEnum.OfferID, sOfferID); childValuemap.setString(O2GRequestParamsEnum.BuySell, Constants.Sell); batchValuemap.appendChild(childValuemap); break; } } request = requestFactory.createOrderRequest(batchValuemap); if (request == null) { Console.WriteLine(requestFactory.getLastError()); } return(request); }
/// <summary> /// Creates a new trade order. /// </summary> /// <param name="symbol">Name of the cryptocurrency asset symbol.</param> /// <param name="bidPrice">The price to bid for this order.</param> /// <param name="amount">The amount of assets to be traded.</param> /// <param name="side">Type of the order that will be created.</param> /// <returns>The order identification number.</returns> public abstract Task <long> CreateOrder(string symbol, double bidPrice, double amount, OrderSide side);
/// <summary> /// ctor /// </summary> /// <param name="sAccountID"></param> /// <param name="side"></param> public CloseOrdersData(string sAccountID, OrderSide side) { mAccountID = sAccountID; mSide = side; }
/// <summary> /// Creates new order for execution using Alpaca REST API endpoint. /// </summary> /// <param name="symbol">Order asset name.</param> /// <param name="quantity">Order quantity.</param> /// <param name="side">Order side (buy or sell).</param> /// <param name="type">Order type.</param> /// <param name="duration">Order duration.</param> /// <param name="limitPrice">Order limit price.</param> /// <param name="stopPrice">Order stop price.</param> /// <param name="clientOrderId">Client order ID.</param> /// <param name="extendedHours">Whether or not this order should be allowed to execute during extended hours trading.</param> /// <param name="orderClass">Order class for advanced order types.</param> /// <param name="takeProfitLimitPrice">Profit taking limit price for advanced order types.</param> /// <param name="stopLossStopPrice">Stop loss stop price for advanced order types.</param> /// <param name="stopLossLimitPrice">Stop loss limit price for advanced order types.</param> /// <param name="nested">Whether or not child orders should be listed as 'legs' of parent orders. (Advanced order types only.)</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Read-only order information object for newly created order.</returns> public async Task <IOrder> PostOrderAsync( String symbol, Int64 quantity, OrderSide side, OrderType type, TimeInForce duration, Decimal?limitPrice = null, Decimal?stopPrice = null, String?clientOrderId = null, Boolean?extendedHours = null, OrderClass?orderClass = null, Decimal?takeProfitLimitPrice = null, Decimal?stopLossStopPrice = null, Decimal?stopLossLimitPrice = null, Boolean?nested = false, CancellationToken cancellationToken = default) { if (clientOrderId != null && clientOrderId.Length > 48) { clientOrderId = clientOrderId.Substring(0, 48); } JsonNewOrderAdvancedAttributes?takeProfit = null, stopLoss = null; if (takeProfitLimitPrice != null) { takeProfit = new JsonNewOrderAdvancedAttributes { LimitPrice = takeProfitLimitPrice }; } if (stopLossStopPrice != null || stopLossLimitPrice != null) { stopLoss = new JsonNewOrderAdvancedAttributes { StopPrice = stopLossStopPrice, LimitPrice = stopLossLimitPrice }; } var newOrder = new JsonNewOrder { Symbol = symbol, Quantity = quantity, OrderSide = side, OrderType = type, TimeInForce = duration, LimitPrice = limitPrice, StopPrice = stopPrice, ClientOrderId = clientOrderId, ExtendedHours = extendedHours, OrderClass = orderClass, TakeProfit = takeProfit, StopLoss = stopLoss, }; var builder = new UriBuilder(_httpClient.BaseAddress) { Path = _httpClient.BaseAddress.AbsolutePath + "orders", Query = new QueryBuilder() .AddParameter("nested", nested) }; await _alpacaRestApiThrottler.WaitToProceed(cancellationToken).ConfigureAwait(false); using var content = toStringContent(newOrder); using var response = await _httpClient.PostAsync( new Uri ("orders", UriKind.RelativeOrAbsolute), content, cancellationToken) .ConfigureAwait(false); return(await response.DeserializeAsync <IOrder, JsonOrder>() .ConfigureAwait(false)); }
// 在对手价上加一定跳数 private double GetPrice(OrderSide side, double jump) { double price = GetPrice(side); if (side == OrderSide.Buy) { price += jump * Instrument.TickSize; } else { price -= jump * Instrument.TickSize; } return price; }
public Order StopLimitOrder(Instrument instrument, OrderSide side, double qty, double limitPrice, double stopPrice, string text) { SingleOrder singleOrder; if (side == OrderSide.Buy) { singleOrder = new StopLimitOrder(instrument.instrument, Side.Buy, qty, limitPrice, stopPrice, text); } else { singleOrder = new StopLimitOrder(instrument.instrument, Side.Sell, qty, limitPrice, stopPrice, text); } singleOrder.Strategy = this.strategyName; Order order = new Order(singleOrder); order.Portfolio = this.portfolio; Map.OQ_SQ_Order[order] = singleOrder; Map.SQ_OQ_Order[singleOrder] = order; return order; }
public static DictionaryObject MakeOrder(PrivateKeyAccount sender, string matcherKey, OrderSide side, Asset amountAsset, Asset priceAsset, decimal price, decimal amount, DateTime expiration, decimal matcherFee) { long timestamp = Utils.CurrentTimestamp(); var stream = new MemoryStream(); var writer = new BinaryWriter(stream); writer.Write(sender.PublicKey); writer.Write(Base58.Decode(matcherKey)); writer.WriteAsset(amountAsset.Id); writer.WriteAsset(priceAsset.Id); writer.Write((byte)(side == OrderSide.Buy ? 0x0 : 0x1)); writer.WriteLong(Asset.PriceToLong(amountAsset, priceAsset, price)); writer.WriteLong(amountAsset.AmountToLong(amount)); writer.WriteLong(timestamp); writer.WriteLong(expiration.ToLong()); writer.WriteLong(Assets.TN.AmountToLong(matcherFee)); var signature = sender.Sign(stream); return(new DictionaryObject { { "senderPublicKey", Base58.Encode(sender.PublicKey) }, { "matcherPublicKey", matcherKey }, { "assetPair", new DictionaryObject { { "amountAsset", amountAsset.IdOrNull }, { "priceAsset", priceAsset.IdOrNull } } }, { "orderType", side.ToString().ToLower() }, { "price", Asset.PriceToLong(amountAsset, priceAsset, price) }, { "amount", amountAsset.AmountToLong(amount) }, { "timestamp", timestamp }, { "expiration", expiration.ToLong() }, { "matcherFee", Assets.TN.AmountToLong(matcherFee) }, { "signature", signature.ToBase58() } }); }
public void SendStopLimitOrder(Instrument instrument, OrderSide side, double qty, double limitPrice, double stopPrice) { this.StopLimitOrder(instrument, side, qty, limitPrice, stopPrice).Send(); }
public bool HasValidQuotes(OrderSide side) { return(side == OrderSide.Buy ? !AskBars[0].IsNull && !double.IsNaN(Ask) : !BidBars[0].IsNull && !double.IsNaN(Bid)); }
public double BestPrice(OrderSide side) { return(side == OrderSide.Buy ? Ask : Bid); }
public double RoundPrice(double price, OrderSide side, int extraDigits = 0) { return(ApiSymbol.RoundPrice(price, side, extraDigits)); }
/// <summary> /// /// </summary> /// <param name="orderSide"></param> /// <param name="qty"></param> /// <param name="name"></param> /// <param name="limitPrice"></param> /// <returns></returns> protected Order CreateOrder(OrderSide orderSide, double qty, string name, double? limitPrice) { Order returnValue = null; if (UseMarketOrder) returnValue = MarketOrder(orderSide, qty, name + "--MARKET--"); else returnValue = LimitOrder(orderSide, qty, limitPrice.Value, name); return returnValue; }
public static OrderPOSTRequestParams CreateSimpleMarket(string symbol, int quantity, OrderSide side) { return(new OrderPOSTRequestParams { Symbol = symbol, Side = Enum.GetName(typeof(OrderSide), side), OrderQty = quantity, OrdType = Enum.GetName(typeof(OrderType), OrderType.Market), }); }
private bool ArePriceActionIndicatorsInFavorableMode(OrderSide orderAction) { bool areIndicatorsFavorable = false; bool isEmaFired = false; bool isStochFired = false; string expectingIndicatorMode = string.Empty; bool almostInd = false; if (orderAction == OrderSide.Buy) { expectingIndicatorMode = "Bullish"; isEmaFired = IsEmaCrossUp && !IsEmaAlmostCrossDn; isStochFired = IsNormalizedStochInBullishMode; almostInd = IsEmaAlmostCrossDn; // We are buying - check for bullish signs areIndicatorsFavorable = (isEmaFired && isStochFired) || (IsStochInOverBoughtMode && !IsEmaAlmostCrossDn) || (IsStochInOverSoldMode && IsEmaAlmostCrossUp && !IsEmaAlmostCrossDn) || (IsStochInOverSoldMode && isEmaFired); } else { expectingIndicatorMode = "Bearish"; isEmaFired = IsEmaCrossDn && !IsEmaAlmostCrossUp; isStochFired = IsNormalizedStochInBearishMode; almostInd = IsEmaAlmostCrossUp; // We are selling - check for bullish signs areIndicatorsFavorable = (isEmaFired && isStochFired) || (IsStochInOverSoldMode && !IsEmaAlmostCrossUp) || (IsStochInOverBoughtMode && IsEmaAlmostCrossDn && !IsEmaAlmostCrossUp) || (IsStochInOverBoughtMode && isEmaFired); } string emaPart = string.Format("EMA({0}x{1})=({2:F4}x{3:F4})={4}. ALMOST EMA={5}", FastMaPeriod, SlowMaPeriod, FastEmaIndicator.Last, SlowEmaIndicator.Last, isEmaFired.ToString().ToUpper(), almostInd.ToString().ToUpper()); string stochPart = string.Format("STOCH({0},{1},{2})=(K={3:F4},D={4:F4})={5}", StochasticsKPeriod, StochasticsDPeriod, StochasticsSmoothPeriod, KSlowIndicator.Last, DSlowIndicator.Last, isStochFired.ToString().ToUpper()); string logMessage = string.Format("INDICATORS (Expecting={0})={1} ({2}, {3})", expectingIndicatorMode, areIndicatorsFavorable.ToString().ToUpper(), emaPart, stochPart ); if (areIndicatorsFavorable) { LoggingUtility.WriteInfo(this, logMessage); } else { WriteInfrequentDebugMessage(logMessage); } return areIndicatorsFavorable; }
/// <summary> /// Be aware that bitmex takes fee for hiden limit orders /// </summary> public static OrderPOSTRequestParams CreateSimpleHidenLimit(string symbol, int quantity, decimal price, OrderSide side) { return(new OrderPOSTRequestParams { Symbol = symbol, Side = Enum.GetName(typeof(OrderSide), side), OrderQty = quantity, OrdType = Enum.GetName(typeof(OrderType), OrderType.Limit), DisplayQty = 0, Price = price, ExecInst = "ParticipateDoNotInitiate", }); }
/// <summary> /// Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. /// </summary> /// <param name="symbol">Ticker symbol.</param> /// <param name="quantity">Quantity to transaction.</param> /// <param name="price">Price of the transaction.</param> /// <param name="orderType">Order type (LIMIT-MARKET).</param> /// <param name="side">Order side (BUY-SELL).</param> /// <param name="timeInForce">Indicates how long an order will remain active before it is executed or expires.</param> /// <param name="recvWindow">Specific number of milliseconds the request is valid for.</param> /// <returns></returns> public async Task <dynamic> PostNewOrderTest(string symbol, decimal quantity, decimal price, OrderSide side, OrderType orderType = OrderType.LIMIT, TimeInForce timeInForce = TimeInForce.GTC, string clientOrderId = null, decimal icebergQty = 0m, long recvWindow = 5000) { //Validates that the order is valid. ValidateOrderValue(symbol, orderType, price, quantity, icebergQty); //quantity needs to be conform to this regex ^([0-9]{1,20})(\.[0-9]{1,20})?$ -> 20 decimal digits quantity = quantity / 1.000000000000000000000000000000m; price = price / 1.000000000000000000000000000000m; var args = $"symbol={symbol.ToUpper()}&side={side}&type={orderType}" + $"&quantity={quantity}" + (orderType == OrderType.LIMIT ? $"&timeInForce={timeInForce}" : "") + (orderType == OrderType.LIMIT ? $"&price={price}" : "") + (clientOrderId != null ? $"&newClientOrderId ={clientOrderId}" : "") + (icebergQty > 0m ? $"&icebergQty={icebergQty}" : "") + $"&recvWindow={recvWindow}"; var result = await _apiClient.CallAsync <dynamic>(ApiMethod.POST, EndPoints.NewOrderTest, true, args); return(result); }
// 得到当前对手价 private double GetPrice(OrderSide side) { Quote quote = Quote; Trade trade = Trade; Bar bar = Bar; if (quote != null) { if (side == OrderSide.Buy) { if (quote.Ask != 0) return quote.Ask; } else { if (quote.Bid != 0) return quote.Bid; } } if (trade != null) if (trade.Price != 0) return trade.Price; if (bar != null) { if (bar.Close != 0) return bar.Close; if (bar.Open != 0) return bar.Open; } return 0; }
public PhysicalOrderDefault(OrderState orderState, SymbolInfo symbol, LogicalOrder logical, OrderSide side, int size) { this.orderState = orderState; this.symbol = symbol; this.side = side; this.type = logical.Type; this.price = logical.Price; this.size = size; this.logicalOrderId = logical.Id; this.logicalSerialNumber = logical.SerialNumber; this.tag = logical.Tag; this.reference = null; this.replace = null; this.brokerOrder = CreateBrokerOrderId(logicalOrderId); }
// 下单操作 private void SendOrder(OrderSide side, EnumOpenClose oc, double qty) { if (qty <= 0) { return; } // 为减少滑点,对数量少的单子直接市价单 bool bMarketOrder = false; if (EnumOpenClose.OPEN == oc) { if (qty <= MarketOpenPriceThreshold) bMarketOrder = true; } else { if (qty <= MarketClosePriceThreshold) bMarketOrder = true; } if (bMarketOrder) { SendMarketOrder(side, qty, OpenCloseHelper.GetOpenCloseString(oc)); } else { SendLimitOrder(side, qty, GetPrice(side, 2), OpenCloseHelper.GetOpenCloseString(oc)); } }
public OrderCreated(Guid modelId, Guid accountId, OrderSide side, string symbol, uint quantity, decimal price) : base(modelId, 1) => (AccountId, Side, Symbol, Quantity, Price) = (accountId, side, symbol, quantity, price);