public PositionInfo(string code, PositionSide positionSide, int position, double positionCost) { this.InstrumentID = code; this.Side = positionSide; this.Position = position; this.PositionCost = positionCost; }
public RoundTrip(Position Position, Instrument Instrument, PositionSide TradePosition, double Amount, double EntryPrice, double ExitPrice, DateTime EntryDateTime, DateTime ExitDateTime, RoundTripStatus Status) : base() { this.position = Position; this.instrument = Instrument; this.tradePosition = TradePosition; this.amount = Amount; this.entryPrice = EntryPrice; this.exitPrice = ExitPrice; this.entryDateTime = EntryDateTime; this.exitDateTime = ExitDateTime; this.entryCost = 0.0; this.exitCost = 0.0; this.entryValue = EntryPrice * Amount; this.exitValue = ExitPrice * Amount; this.roundTripLowPrice = EntryPrice; this.roundTripHighPrice = EntryPrice; this.status = Status; if (this.status != RoundTripStatus.Opened) { return; } this.series = new DoubleSeries(); this.series.Add(EntryDateTime, this.entryPrice); this.Connect(); }
public void RemovePosition(string codeId, PositionSide positionSide) { int rowNum = IndexPosition(codeId, positionSide); this.positions.RemoveAt(rowNum); this.gridPosition.Rows.RemoveAt(rowNum); }
private bool BasketAlignment() { List <PercentItem> temp = new List <PercentItem>(); OrderSide side = OrderSide.Buy; PositionSide positionSide = PositionSide.Both; string sideName = ""; decimal OrderVolume = 0; if (Weights > 0) { // перекос в сторону лонга идем в шорт foreach (var it in Percents) { if (it.Short) { temp.Add(it); } } side = OrderSide.Sell; sideName = "Short"; positionSide = PositionSide.Short; } else if (Weights < 0) { // перекос в сторону шорта идем в лонг foreach (var it in Percents) { if (it.Long) { temp.Add(it); } } side = OrderSide.Buy; sideName = "Long"; positionSide = PositionSide.Long; } else if (Weights == 0) { Log.Add("Alignment is not required", Color.Green); return(false); } PercentItem PairAlign = new PercentItem(); if (side == OrderSide.Sell) { if (temp.Count != 0) { PairAlign = temp[0]; } else { Log.Add("Error! there are no positions in " + sideName + ". Closing all positions", Color.OrangeRed); return(true); } } else if (side == OrderSide.Buy) { if (temp.Count != 0) { PairAlign = temp[^ 1];
public void Enter(Quote quote, SingleOrder order) { latestQuote = quote; order.ExecutionReport += new ExecutionReportEventHandler(order_ExecutionReport); EntryOrder = order; if (State.Created == state) { } else { Console.WriteLine("*** {0} RoundTrip.Enter in {1}", instrument.Symbol, state); } //Console.WriteLine( "setting entry submitted" ); state = State.EntrySubmitted; dtEntryInitiation = quote.DateTime; quoteEntryInitiation = quote; if (order.Side == Side.Buy) { side = PositionSide.Long; } if (order.Side == Side.Sell || order.Side == Side.SellShort) { side = PositionSide.Short; } // need an error condition here }
/// <summary> /// Slices this collection, returning a new collection containing only /// positions with the specified <paramref name="side"/> /// </summary> public OptionPositionCollection Slice(PositionSide side, bool includeUnderlying = true) { var otherSides = GetOtherSides(side); var sides = _sides.Remove(otherSides[0]).Remove(otherSides[1]); var positions = ImmutableDictionary <Symbol, OptionPosition> .Empty; if (includeUnderlying && HasUnderlying) { positions = positions.Add(Underlying, UnderlyingPosition); } var rights = ImmutableDictionary <OptionRight, ImmutableHashSet <Symbol> > .Empty; var strikes = ImmutableSortedDictionary <decimal, ImmutableHashSet <Symbol> > .Empty; var expirations = ImmutableSortedDictionary <DateTime, ImmutableHashSet <Symbol> > .Empty; foreach (var symbol in sides.SelectMany(kvp => kvp.Value)) { var position = _positions[symbol]; rights = rights.Add(position.Right, symbol); positions = positions.Add(symbol, position); strikes = strikes.Add(position.Strike, symbol); expirations = expirations.Add(position.Expiration, symbol); } return(new OptionPositionCollection(positions, rights, sides, strikes, expirations)); }
public void Initializes_OptionRight(PositionSide side) { // grab a random symbol and make it the correct right var quantity = (int)side; var position = new OptionPosition(Call[100], quantity); Assert.AreEqual(side, position.Side); }
public Position(Symbol symbol, double openPrice, double size, PositionSide side, DateTime openDate) { Symbol = symbol; PositionPrice = openPrice; Side = side; Size = size; OpenDate = openDate; }
/// <summary> /// Returns the set of <see cref="OptionPosition"/> with the specified <paramref name="side"/> /// </summary> public IEnumerable <OptionPosition> ForSide(PositionSide side) { ImmutableHashSet <Symbol> symbols; return(_sides.TryGetValue(side, out symbols) ? ForSymbols(symbols) : Enumerable.Empty <OptionPosition>()); }
public Trade(DateTime begin, DateTime end, PositionSide side, double openPrice, double closePrice) { Begin = begin; End = end; Side = side; OpenPrice = openPrice; ClosePrice = closePrice; }
public QBStop(Strategy strategy, Position position, PositionSide side, double qty, DateTime time) : base(strategy, position, time) { if (qty > 0) { this.qty = qty; } this.side = side; }
/// <summary> /// Helper method for SampleExposure, samples our holdings value to /// our exposure chart by their position side and security type /// </summary> /// <param name="type">Side to sample from portfolio</param> /// <param name="time">Time of the sample</param> /// <param name="currentPortfolioValue">Current value of the portfolio</param> /// <param name="holdings">Enumerable of holdings to sample</param> private void SampleExposureHelper(PositionSide type, DateTime time, decimal currentPortfolioValue, Dictionary <SecurityType, decimal> holdings) { foreach (var kvp in holdings) { var ratio = Math.Round(kvp.Value / currentPortfolioValue, 4); Sample("Exposure", $"{kvp.Key} - {type} Ratio", 0, SeriesType.Line, time, ratio, ""); } }
public Position(PositionSide positionSide, DateTime dateTime, decimal price, int size, decimal?takeProfitPoints = null, decimal?stopLossPoints = null) { Side = positionSide; OpenDateTime = dateTime; OpenPrice = price; Size = size; TakeProfitPoints = takeProfitPoints; InitializeTakeProfit(OpenPrice); StopLossPoints = stopLossPoints; InitializeStopLoss(OpenPrice); }
private static Side ToCommonPositionSide(PositionSide side) { switch (side) { case PositionSide.Long: return(Side.Buy); case PositionSide.Short: return(Side.Sell); default: throw new ArgumentException("Unsupported position side", nameof(side)); } }
public QBStop(Strategy strategy, Position position, PositionSide side, double qty, double level, StopType type, StopMode mode) : base(strategy, position, level, type, mode) { if (qty > 0) { this.qty = qty; } this.side = side; }
private int IndexPosition(string codeId, PositionSide positionSide) { for (int i = 0; i < positions.Count; i++) { PositionInfo positionInfo = positions[i]; if (positionInfo.InstrumentID.Equals(codeId) && positionInfo.Side == positionSide) { return(i); } } return(-1); }
public virtual double GetExposure(int tag, string val, PositionSide side) { double num = 0.0; foreach (Position position in (IEnumerable)this.positions.Clone()) { if (position.Side == side && position.Instrument.GetStringField(tag).Value == val) { num += position.GetValue(); } } return(num / this.GetPositionValue()); }
private TradeResult OperationHandler(PositionSide operationType) { var instrument = HistoryDataSeries.HistoricalRequest.Instrument; TradeResult tradeResult = null; if (tradeStatus == TradeStatus.Allow) { var newOperation = operationType == PositionSide.Short ? OrderSide.Sell : OrderSide.Buy; var price = operationType == PositionSide.Short ? instrument.DayInfo.Bid : instrument.DayInfo.Ask; tradeResult = SendOrder(OrderType.Market, newOperation, price, lotSize); } return(tradeResult); }
private static PositionSide[] GetOtherSides(PositionSide side) { switch (side) { case PositionSide.Short: return(OtherSidesForShort); case PositionSide.None: return(OtherSidesForNone); case PositionSide.Long: return(OtherSidesForLong); default: throw new ArgumentOutOfRangeException(nameof(side), side, null); } }
public Stop(Strategy strategy, Position position, DateTime time) { this.strategy = strategy; this.position = position; this.instrument = position.instrument; this.qty = position.qty; this.side = position.Side; this.type = StopType.Time; this.creationTime = strategy.framework.Clock.DateTime; this.completionTime = time; this.stopPrice = this.GetInstrumentPrice(); if (this.completionTime > this.creationTime) { strategy.framework.Clock.AddReminder(new Reminder(new ReminderCallback(this.OnClock), this.completionTime, null)); } }
private Stop(Strategy strategy, Position position, DateTime time, double level = 0, StopType type = StopType.Trailing, StopMode mode = StopMode.Percent) { this.strategy = strategy; this.position = position; this.instrument = position.Instrument; this.qty = position.Qty; this.side = position.Side; this.type = type; this.mode = mode; this.creationTime = strategy.framework.Clock.DateTime; this.completionTime = time; this.stopPrice = GetInstrumentPrice(); if (this.completionTime > this.creationTime) { strategy.framework.Clock.AddReminder(new Reminder(this.method_9, this.completionTime, null)); } }
public Stop(Strategy strategy, Position position, double level, StopType type, StopMode mode) { this.strategy = strategy; this.position = position; this.instrument = position.instrument; this.qty = position.qty; this.side = position.Side; this.level = level; this.type = type; this.mode = mode; this.currPrice = this.GetInstrumentPrice(); this.trailPrice = this.currPrice; this.stopPrice = this.GetStopPrice(); this.creationTime = strategy.framework.Clock.DateTime; this.completionTime = DateTime.MinValue; this.Connect(); }
internal bool IsExitStopPriceMet(double lastPrice, double stopPrice, PositionSide positionSide) { bool stopMet = false; if (positionSide == PositionSide.Short) 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, positionSide, lastPrice)); return stopMet; }
public RoundTrip(Position Position, Instrument Instrument, PositionSide TradePosition, double Amount, double EntryPrice, double ExitPrice, DateTime EntryDateTime, DateTime ExitDateTime) : base() { this.position = Position; this.instrument = Instrument; this.tradePosition = TradePosition; this.amount = Amount; this.entryPrice = EntryPrice; this.exitPrice = ExitPrice; this.entryDateTime = EntryDateTime; this.exitDateTime = ExitDateTime; this.entryCost = 0.0; this.exitCost = 0.0; this.entryValue = EntryPrice * Amount; this.exitValue = ExitPrice * Amount; this.roundTripLowPrice = EntryPrice; this.roundTripHighPrice = EntryPrice; this.status = RoundTripStatus.Closed; }
internal void method_3(Bar bar_0) { if (this.traceOnBar && (this.filterBarSize < 0L || (this.filterBarSize == bar_0.Size && this.filterBarType == BarType.Time))) { this.trailPrice = this.GetPrice(bar_0.Close); PositionSide positionSide = this.side; if (positionSide != PositionSide.Long) { if (positionSide == PositionSide.Short) { this.currPrice = this.GetPrice(bar_0.High); this.fillPrice = this.currPrice; if (this.trailOnHighLow) { this.trailPrice = this.GetPrice(bar_0.Low); } } } else { this.currPrice = this.GetPrice(bar_0.Low); this.fillPrice = this.currPrice; if (this.trailOnHighLow) { this.trailPrice = this.GetPrice(bar_0.High); } } StopFillMode stopFillMode = this.fillMode; if (stopFillMode != StopFillMode.Close) { if (stopFillMode == StopFillMode.Stop) { this.fillPrice = this.stopPrice; } } else { this.fillPrice = this.GetPrice(bar_0.Close); } this.method_1(); } }
private void method_1() { if (this.currPrice == 0.0) { return; } PositionSide positionSide = this.side; if (positionSide != PositionSide.Long) { if (positionSide != PositionSide.Short) { return; } if (this.currPrice >= this.stopPrice) { this.Disconnect(); this.method_8(StopStatus.Executed); return; } if (this.type == StopType.Trailing && this.trailPrice < this.initPrice) { this.stopPrice = this.GetStopPrice(); } } else { if (this.currPrice <= this.stopPrice) { this.Disconnect(); this.method_8(StopStatus.Executed); return; } if (this.type == StopType.Trailing && this.trailPrice > this.initPrice) { this.stopPrice = this.GetStopPrice(); return; } } }
public void Enter(Quote quote, SingleOrder Order) { quoteLatest = quote; Order.ExecutionReport += new ExecutionReportEventHandler(order_ExecutionReport); this.Order = Order; if (EState.Created != state) { throw new InvalidOperationException("ExecutionStatistics already 'Enter'd " + instrument.Symbol + ", " + state); } state = EState.Submitted; quoteInitiation = quote; if (Order.Side == Side.Buy) { side = PositionSide.Long; } if (Order.Side == Side.Sell || Order.Side == Side.SellShort) { side = PositionSide.Short; } // need an error condition here }
protected virtual double GetStopPrice() { this.initPrice = this.trailPrice; StopMode stopMode = this.mode; if (stopMode != StopMode.Absolute) { if (stopMode != StopMode.Percent) { throw new ArgumentException("Unknown stop mode : " + this.mode); } PositionSide positionSide = this.position.Side; if (positionSide == PositionSide.Long) { return(this.trailPrice - Math.Abs(this.trailPrice * this.level)); } if (positionSide != PositionSide.Short) { throw new ArgumentException("Unknown position side : " + this.position.Side); } return(this.trailPrice + Math.Abs(this.trailPrice * this.level)); } else { PositionSide positionSide = this.side; if (positionSide == PositionSide.Long) { return(this.trailPrice - Math.Abs(this.level)); } if (positionSide != PositionSide.Short) { throw new ArgumentException("Unknown position side : " + this.position.Side); } return(this.trailPrice + Math.Abs(this.level)); } }
protected bool IsExitStopPriceMet(double lastPrice, double stopPrice, PositionSide positionSide) { bool stopMet = false; if (positionSide == PositionSide.Short) stopMet = lastPrice >= stopPrice; else stopMet = lastPrice <= stopPrice; return stopMet; }
protected void AddPositionSize(string symbol, PositionSide positionSide, double positionSize) { if (string.Compare(Instrument.Symbol, symbol, StringComparison.InvariantCultureIgnoreCase) == 0) { double qty = (positionSide == PositionSide.Long) ? Math.Abs(positionSize) : Math.Abs(positionSize)*-1; PositionSizeManager.AddPositionSize(symbol, qty); LoggingUtility.WriteDebug(LoggingConfig, string.Format("Added a position size of {0}", positionSize)); } }
public RoundTrip(Position Position, Instrument Instrument, PositionSide TradePosition, double Amount, double EntryPrice, double ExitPrice, DateTime EntryDateTime, DateTime ExitDateTime, RoundTripStatus Status) : base() { this.position = Position; this.instrument = Instrument; this.tradePosition = TradePosition; this.amount = Amount; this.entryPrice = EntryPrice; this.exitPrice = ExitPrice; this.entryDateTime = EntryDateTime; this.exitDateTime = ExitDateTime; this.entryCost = 0.0; this.exitCost = 0.0; this.entryValue = EntryPrice * Amount; this.exitValue = ExitPrice * Amount; this.roundTripLowPrice = EntryPrice; this.roundTripHighPrice = EntryPrice; this.status = Status; if (this.status != RoundTripStatus.Opened) return; this.series = new DoubleSeries(); this.series.Add(EntryDateTime, this.entryPrice); this.Connect(); }
public RoundTrip(Position Position, Instrument Instrument, PositionSide TradePosition, double Amount, double EntryPrice, double ExitPrice, DateTime EntryDateTime, DateTime ExitDateTime) :base() { this.position = Position; this.instrument = Instrument; this.tradePosition = TradePosition; this.amount = Amount; this.entryPrice = EntryPrice; this.exitPrice = ExitPrice; this.entryDateTime = EntryDateTime; this.exitDateTime = ExitDateTime; this.entryCost = 0.0; this.exitCost = 0.0; this.entryValue = EntryPrice * Amount; this.exitValue = ExitPrice * Amount; this.roundTripLowPrice = EntryPrice; this.roundTripHighPrice = EntryPrice; this.status = RoundTripStatus.Closed; }
private Stop(Strategy strategy, Position position, DateTime time, double level = 0, StopType type = StopType.Trailing, StopMode mode = StopMode.Percent) { this.strategy = strategy; this.position = position; this.instrument = position.Instrument; this.qty = position.Qty; this.side = position.Side; this.type = type; this.mode = mode; this.creationTime = strategy.framework.Clock.DateTime; this.completionTime = time; this.stopPrice = GetInstrumentPrice(); if (this.completionTime > this.creationTime) strategy.framework.Clock.AddReminder(new Reminder(this.method_9, this.completionTime, null)); }
public void MarginRequirementEs(decimal strike, double expected, OptionRight optionRight, PositionSide positionSide, decimal underlyingRequirement) { var tz = TimeZones.NewYork; var expDate = new DateTime(2021, 3, 19); // For this symbol we dont have any history, but only one date and margins line var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini; var future = Symbol.CreateFuture(ticker, Market.Globex, expDate); var symbol = Symbol.CreateOption(future, Market.Globex, OptionStyle.American, optionRight, strike, new DateTime(2021, 3, 19)); var futureSecurity = new Future( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); var optionSecurity = new QuantConnect.Securities.FutureOption.FutureOption(symbol, SecurityExchangeHours.AlwaysOpen(tz), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache(), futureSecurity ); optionSecurity.Underlying.SetMarketPrice(new Tick { Value = 4172, Time = new DateTime(2001, 01, 07) }); var marginRequirement = FuturesOptionsMarginModel.GetMarginRequirement(optionSecurity, underlyingRequirement, positionSide); Log.Debug($"Side {positionSide}. Right {optionRight}. Strike {strike}. Margin: {marginRequirement}"); Assert.AreEqual(expected, marginRequirement, (double)underlyingRequirement * 0.30d); }
public bool HasPosition(PositionSide side, double qty) => base.HasPosition(Instrument, side, qty);
public double CalculateStopSlippageAdjustedPrice(double amount, double atr, double allowedSlippage, PositionSide side) { double slippageAmount = atr * allowedSlippage; double returnValue = amount; if (side == PositionSide.Long) { returnValue = returnValue - slippageAmount; } else { returnValue = returnValue + slippageAmount; } LoggingUtility.WriteInfo( logConfig, string.Format( "Allowed STOP slippage is {0}x ATR {1:c} ({2:p}) = {3:c} ({4:p}) on price of {5:c}, so slippage adjusted price is {6:c}", allowedSlippage, atr, atr/amount, slippageAmount, slippageAmount/amount, amount, returnValue)); return returnValue; }
public bool HasPosition(Instrument instrument, PositionSide side, double qty) { return this.Portfolio.HasPosition(instrument, side, qty); }
public virtual double GetExposure(int tag, string val, PositionSide side) { double num = 0.0; foreach (Position position in (IEnumerable) this.positions.Clone()) { if (position.Side == side && position.Instrument.GetStringField(tag).Value == val) num += position.GetValue(); } return num / this.GetPositionValue(); }
public ProjectToRun WithSpecificPositionSideToReverse(PositionSide side) { this.specificPosSide = side; return this; }
public static void AddPositionSize(string symbol, PositionSide positionSide, double positionSize) { double qty = (positionSide == PositionSide.Long) ? Math.Abs(positionSize) : Math.Abs(positionSize)*-1; PositionSizeHolder.AddPositionSize(symbol, qty); }
public virtual int GetQntContracts(double enterPrice, double stopPrice, PositionSide position) { logger.Log("enterPrice = " + enterPrice.ToString()); logger.Log("stopPrice = " + stopPrice.ToString()); logger.Log("position = " + position.ToString()); var go = 0.0; switch (position) { case PositionSide.Long: { if (stopPrice >= enterPrice) { return(0); } go = account.GObying; logger.Log("go = " + go.ToString()); } break; case PositionSide.Short: { if (stopPrice <= enterPrice) { return(0); } go = account.GOselling; } break; case PositionSide.LongAndShort: break; } var money = globalMoneyManager.GetMoneyForDeal(); logger.Log("money = " + money.ToString()); var riskMoney = Math.Abs(enterPrice - stopPrice); logger.Log("riskMoney = " + riskMoney.ToString()); var contractsByGO = (int)(globalMoneyManager.FreeBalance / go); // надо вычислять это значение исходя из общего депозита logger.Log("contractsByGO = " + contractsByGO.ToString()); if (currency == Currency.USD) { money = money / account.Rate; } logger.Log("money = " + money.ToString()); var contractsByRiskMoney = (int)(money / riskMoney); logger.Log("contractsByRiskMoney = " + contractsByRiskMoney.ToString()); var min = Math.Min(contractsByRiskMoney, contractsByGO); if (min >= 0) { return(min); } else { return(0); } }
public bool HasPosition(Instrument instrument, PositionSide side, double qty) { Position position = this.positionByInstrument[instrument.Id]; return position != null && position.Side == side && position.qty == qty; }
public bool HasPosition(PositionSide side, double qty) { return this.strategy.HasPosition(Instrument, side, qty); }