/// <summary> /// Register ISourceDataDelivery. /// </summary> protected bool AddElement(ComponentId id, ISourceDataDelivery delivery) { if (id.IsEmpty || delivery == null) { SystemMonitor.Warning("Invalid Id or data delivery instance."); return(false); } lock (this) { if (_dataDeliveries.ContainsKey(id)) { SystemMonitor.Warning("Failed to add data delivery, since already added with this Id."); return(false); } foreach (ComponentId deliveryId in _dataDeliveries.Keys) { SystemMonitor.CheckThrow(id.Name.ToLower() == id.Name.ToLower(), "Data Delivery with this name Id already present [" + id.Name + "]."); } _dataDeliveries.Add(id, delivery); } return(true); }
/// <summary> /// Wrap those operations to handle cases like nullable, or types that do not persist /// directly like the TimeSpan. /// In the case of getting no direct conversions needed. /// </summary> object HandleGetValue(IDBPersistent item, PropertyInfo info) { DBPersistenceAttribute[] dbPersistence = (DBPersistenceAttribute[])info.GetCustomAttributes(typeof(DBPersistenceAttribute), true); if (dbPersistence.Length > 0) { SystemMonitor.CheckThrow(dbPersistence.Length == 1 && dbPersistence[0].PersistenceType != DBPersistenceAttribute.PersistenceTypeEnum.None, "Misteken usage of persistence attributes or internal error."); if (dbPersistence[0].PersistenceType == DBPersistenceAttribute.PersistenceTypeEnum.Binary) { object val = info.GetValue(item, null); if (val == null) { return(null); } using (MemoryStream ms = new MemoryStream()) {// SaveState object persistance as BYTE[]. SerializationHelper.Serialize(ms, val); ms.Flush(); return(ms.GetBuffer()); } } } // Default case - no specific persistance instructions given. return(info.GetValue(item, null)); }
public void SynchronizeWithMasterPane() { if (_masterPane == null || _masterPaneSynchronizationMode == MasterPaneSynchronizationModeEnum.None) { return; } SystemMonitor.CheckThrow(_masterPaneSynchronizationMode == MasterPaneSynchronizationModeEnum.XAxis, "Mode not supported."); GraphicsWrapper.SynchronizeDrawingSpaceXAxis(_masterPane.GraphicsWrapper); this.YAxisLabelsPosition = _masterPane.YAxisLabelsPosition; //this.AutoScrollToEnd = _masterPane.AutoScrollToEnd; this.LimitedView = _masterPane.LimitedView; Crosshair.Visible = _masterPane.Crosshair.Visible; RectangleF screen = GraphicsWrapper.ActualSpaceToDrawingSpace(ActualDrawingSpaceArea); FitHorizontalAreaToScreen(screen); UpdateMasterSynchronizationState(true); WinFormsHelper.BeginFilteredManagedInvoke(this, TimeSpan.FromMilliseconds(100), Refresh); //this.Invalidate(); }
public bool Initialize() { SystemMonitor.CheckThrow(State == OrderStateEnum.UnInitialized, "Order already initialized."); State = OrderStateEnum.Initialized; return(true); }
/// <summary> /// Startup initialization procedure, called only once in the lifecycle of an object /// (only after initial construction, not upon serialization-deserialization). /// </summary> /// <param name="dataProvider"></param> /// <param name="orderExectionProvider"></param> public bool SetInitialParameters(ISessionDataProvider dataProvider, ISourceOrderExecution orderExectionProvider) { SystemMonitor.CheckThrow(_sessionDataProvider == null && _orderExecutionProvider == null, "Session already initialized."); _sessionDataProvider = dataProvider; _orderExecutionProvider = orderExectionProvider; return(true); }
/// <summary> /// Constructor. /// </summary> public ArbiterSlimActiveClientStub(IArbiterClient client, ArbiterSlimExecutionStrategy executionStrategy) { _client = client; _executionStrategy = executionStrategy; SystemMonitor.CheckThrow(executionStrategy != null, "Execution strategy not assigned."); Construct(); }
/// <summary> /// Constructor, allows direct order initialization. /// </summary> /// <param name="session"></param> /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param> public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider, ComponentId dataSourceId, bool initialize) : base(manager, executionProvider, dataSourceId) { State = OrderStateEnum.UnInitialized; if (initialize) { SystemMonitor.CheckThrow(Initialize()); } }
/// <summary> /// Initialization. /// </summary> public bool Initialize() { SystemMonitor.CheckThrow(State == OrderStateEnum.UnInitialized, "Order already initialized."); ISourceOrderExecution executionProvider = _executionProvider; _quoteProvider.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quote_QuoteUpdateEvent); State = OrderStateEnum.Initialized; return(true); }
/// <summary> /// Constructor. Set slave sessions, this order will put slave orders to. /// </summary> public MasterOrder(IEnumerable <ExpertSession> slaveSessions, VolumeDistributionEnum volumeDistribution, bool initialize) { _slaveSessions.Clear(); _slaveSessions.AddRange(slaveSessions); _volumeDistribution = volumeDistribution; if (initialize) { SystemMonitor.CheckThrow(this.Initialize(), "Failed to initialize order."); } }
/// <summary> /// Set dynamic values. /// </summary> public void SetDynamic(string[] names, object[] values) { SystemMonitor.CheckThrow(names.Length == values.Length); lock (this) { _dynamicValues.Clear(); for (int i = 0; i < names.Length; i++) { _dynamicValues.Add(names[i], values[i]); } } }
/// <summary> /// Wrap those operations to handle cases like nullable, or types that do not persist /// directly like the TimeSpan. /// </summary> bool HandleSetValue(IDBPersistent item, PropertyInfo info, object value) { Type propertyType = info.PropertyType; Type underlyingType = Nullable.GetUnderlyingType(info.PropertyType); if (underlyingType != null) {// Unwrap nullable properties. propertyType = underlyingType; if (value == null) {// Nullable enums with null values not displayed. info.SetValue(item, null, null); return(true); } } object actualValue = value; DBPersistenceAttribute[] dbPersistence = (DBPersistenceAttribute[])info.GetCustomAttributes(typeof(DBPersistenceAttribute), true); if (dbPersistence.Length > 0) { SystemMonitor.CheckThrow(dbPersistence.Length == 1 && dbPersistence[0].PersistenceType != DBPersistenceAttribute.PersistenceTypeEnum.None, "Misteken usage of persistence attributes or internal error."); if (dbPersistence[0].PersistenceType == DBPersistenceAttribute.PersistenceTypeEnum.Binary) {// DeSerialize object persistence from BYTE[]. byte[] byteValue = (byte[])value; SystemMonitor.CheckThrow(byteValue != null || byteValue.Length != 0, "Byte value size not expected at deserialization."); using (MemoryStream ms = new MemoryStream(byteValue)) { if (SerializationHelper.DeSerialize(ms, out actualValue) == false) {// Failed to deserialize. return(false); } } } } else if (propertyType == typeof(TimeSpan)) { actualValue = TimeSpan.Parse(value as string); } else if (propertyType.IsEnum) { actualValue = Enum.ToObject(propertyType, (int)value); } else if (propertyType == typeof(Uri)) { actualValue = new Uri(value as string); } info.SetValue(item, actualValue, null); return(true); }
/// <summary> /// Initialization. /// </summary> public bool Initialize() { SystemMonitor.CheckThrow(State == OrderStateEnum.UnInitialized, "Order already initialized."); ISourceOrderExecution executionProvider = _executionProvider; if (Symbol.IsEmpty == false && QuoteProvider != null) {// This will only work for deserialized orders, or ones that already have adopted info. QuoteProvider.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quote_QuoteUpdateEvent); } State = OrderStateEnum.Initialized; return(true); }
/// <summary> /// Use to create forex pairs symbols. /// </summary> public Symbol(SymbolGroup group, string currency1, string currency2) { SystemMonitor.CheckThrow(group == SymbolGroup.Forex); _name = currency1 + "/" + currency2; _group = group.ToString(); _source = string.Empty; _isForexPair = true; _forexCurrency1 = currency1; _forexCurrency2 = currency2; Construct(); }
/// <summary> /// Helper, initialize a single TaLib indicator. /// </summary> Indicator InitializeTaLibIndicator(MethodInfo methodInfo, string indicatorName, bool?isTradeable, bool?isScaledToQuotes, float?rangeMinimum, float?rangeMaximum, DataBar.DataValueEnum?inRealSource, DataBar.DataValueEnum?inReal1Source, params object[] inputParameters) { lock (this) { MethodInfo lookBackCountMethodInfo = null; foreach (MethodInfo info in typeof(TicTacTec.TA.Library.Core).GetMethods()) { if (info.Name == methodInfo.Name + "Lookback") { lookBackCountMethodInfo = info; break; } } if (lookBackCountMethodInfo == null) { SystemMonitor.Error("Failed to find indicator [" + methodInfo.Name + "] look back method."); return(null); } GenericTALibIndicator indicator = GenericTALibIndicator.CreateInstance(methodInfo, lookBackCountMethodInfo, indicatorName, isTradeable, isScaledToQuotes); if (indicator == null) { SystemMonitor.Error("Creating indicator [" + indicator.Name + "] failed."); return(null); } string[] names = new string[inputParameters.Length]; for (int i = 0; i < inputParameters.Length; i++) { names[i] = "Parameter." + inputParameters[i].GetType().Name + "." + i.ToString(); } SystemMonitor.CheckThrow(indicator.SetInitialParameters(inputParameters, names)); _indicatorsGroups[IndicatorGroup.TaLib].Add(indicator.Name, indicator); indicator.RealInputArraySource = inRealSource; indicator.Real1InputArraySource = inReal1Source; indicator.RangeMinimum = rangeMinimum; indicator.RangeMaximum = rangeMaximum; return(indicator); } }
bool SubmitPositionOrder(OrderTypeEnum orderType, bool synchronous, int volume, decimal?allowedSlippage, decimal?desiredPrice, decimal?sourceTakeProfit, decimal?sourceStopLoss, bool allowExistingOrdersManipulation, string comment, out string operationResultMessage) { SystemMonitor.CheckThrow(SelectedPosition != null, "Selected session must be not null to create orders."); Position position = SelectedPosition.OrderExecutionProvider.TradeEntities.ObtainPositionBySymbol(SelectedPosition.Symbol); if (position == null) { operationResultMessage = "Failed to find position order."; SystemMonitor.Error(operationResultMessage); return(false); } string submitResult = string.Empty; if (synchronous == false) { submitResult = position.Submit(orderType, volume, desiredPrice, allowedSlippage, sourceTakeProfit, sourceStopLoss, out operationResultMessage); } else { PositionExecutionInfo info; if (allowExistingOrdersManipulation) { int directionalVolume = OrderInfo.TypeIsBuy(orderType) ? volume : -volume; submitResult = position.ExecuteMarketBalanced(directionalVolume, desiredPrice, allowedSlippage, TimeSpan.FromSeconds(15), out info, out operationResultMessage); } else { submitResult = position.ExecuteMarket(orderType, volume, desiredPrice, allowedSlippage, sourceTakeProfit, sourceStopLoss, TimeSpan.FromSeconds(15), out info, out operationResultMessage); } } if (string.IsNullOrEmpty(submitResult)) { SystemMonitor.Error("Failed to place order [" + operationResultMessage + "]"); return(false); } return(true); }
/// <summary> /// Start operation. /// A single instance must be able to handle multiple LoadFromFile-Uninitialize cycles. /// And also must be able to operate a LoadFromFile-Uninitialize-SaveState-Deserialize-LoadFromFile etc. cycles. /// </summary> public bool Initialize(Platform platform) { lock (this) {// Multiple init-uninit cycles allowed. SystemMonitor.CheckThrow(_platform == null || _platform == platform); _platform = platform; if (OnInitialize(platform) == false) { _platform = null; return(false); } } SystemMonitor.CheckError(OperationalState == OperationalStateEnum.Operational || OperationalState == OperationalStateEnum.Initialized, "Component not initalized(or operational) after init[true]."); return(true); }
/// <summary> /// Constructor, allows direct order initialization. /// </summary> /// <param name="session"></param> /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param> public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider, IQuoteProvider quoteProvider, ComponentId dataSourceId, Symbol symbol, bool initialize) { _manager = manager; _symbol = symbol; _dataSourceId = dataSourceId; _executionProvider = executionProvider; _quoteProvider = quoteProvider; State = OrderStateEnum.UnInitialized; if (initialize) { SystemMonitor.CheckThrow(Initialize()); } }
/// <summary> /// /// </summary> public bool Delete <ItemType>(IEnumerable <ItemType> items) where ItemType : class, IDBPersistent { TracerHelper.TraceEntry(typeof(ItemType).Name); string tableName = _tablesTypeNames[typeof(ItemType)]; _deleteMutex.WaitOne(); try { using (SQLiteConnection connection = GenerateConnection()) { using (SQLiteCommand command = new SQLiteCommand(connection)) { connection.Open(); using (SQLiteTransaction transaction = connection.BeginTransaction()) { SQLiteParameter whereIdParam = new SQLiteParameter("@ParamId"); command.Parameters.Add(whereIdParam); command.CommandText = "DELETE FROM " + tableName + " WHERE Id = " + whereIdParam.ParameterName; foreach (IDBPersistent persistent in items) { SystemMonitor.CheckThrow(persistent.Id.HasValue, "Deleting an item with no ID already assigned."); whereIdParam.Value = persistent.Id; int result = command.ExecuteNonQuery(); } transaction.Commit(); } } } } finally { _deleteMutex.ReleaseMutex(); } TracerHelper.TraceExit(); return(true); }
public virtual bool Initialize(IDataBarHistoryProvider dataProvider) { SystemMonitor.CheckThrow(_dataProvider == null, "Data provider already assigned."); TracerHelper.Trace(this.Name); lock (this) { _dataProvider = dataProvider; if (_dataProvider != null) { _dataProvider.DataBarHistoryUpdateEvent += new DataBarHistoryUpdateDelegate(_dataProvider_DataBarHistoryUpdateEvent); } if (_parameters != null) { _parameters.ParameterUpdatedValueEvent += new IndicatorParameters.ParameterUpdatedValueDelegate(_parameters_ParameterUpdatedValueEvent); } } return(true); }
private void PlatformComponentControl_Load(object sender, EventArgs e) { if (this.DesignMode) { return; } SystemMonitor.CheckThrow(Tag == _component, "Tag is expected to be component."); labelStatus.Visible = this.IsInherited == false; if (this.IsInherited == false) { _component.OperationalStateChangedEvent += new OperationalStateChangedDelegate(_component_OperationalStateChangedEvent); _component_OperationalStateChangedEvent(_component, OperationalStateEnum.Unknown); } if (_component != null) { this.Name = _component.Name; } }
/// <summary> /// Send container over to the other side. /// </summary> /// <param name="messageContainer"></param> /// <returns></returns> public virtual bool SendMessageContainer(MessageContainer messageContainer) { TracerHelper.TraceEntry("sending [" + messageContainer.MessageStreamLength + "], sessionID[" + this.ConnectionSessionID + "]"); SystemMonitor.CheckThrow(messageContainer.MessageStreamLength <= MessageContainerTransportServer.MaximumAllowedMessageSize, "MessageContainer message is too big. Message will not be sent."); if (_connectingEvent.WaitOne(_defaultConnectionTimeOut) == false) { SystemMonitor.OperationError("Failed to send message due to initialization timeout.", TracerItem.PriorityEnum.Medium); return(false); } try { IMessageContainerTransport messageInterface; lock (this) { if (_proxyServerInterface == null) { TracerHelper.TraceError("Failed to send to server, interface not created."); return(false); } messageInterface = _proxyServerInterface; } messageInterface.ReceiveMessageContainer(messageContainer); lock (this) { _lastServerCall = DateTime.Now; } } catch (Exception exception) { TracerHelper.TraceError("Failed to send to server, reason [" + exception.Message + "]."); return(false); } return(true); }
void _sessionManager_SessionsUpdateEvent(ISourceAndExpertSessionManager sessionManager) { SystemMonitor.CheckThrow(sessionManager == _sessionManager); List <ExpertSession> sessions = new List <ExpertSession>(_sessions); foreach (ExpertSession session in _sessionManager.SessionsArray) { if (sessions.Contains(session) == false) {// Newly added sessionInformation. AddSession(session); } sessions.Remove(session); } foreach (ExpertSession session in sessions) {// Those sessions were not present after the manager was updated. RemoveSession(session); } UpdateUI(); }
public bool Initialize(Uri serverUriBase) { TracerHelper.TraceEntry(); lock (this) { SystemMonitor.CheckThrow(_serviceHost == null, "Already initialized."); try { _serviceHost = new ServiceHost(this); _serviceHost.AddServiceEndpoint(typeof(IMessageContainerTransport), CreateBinding(), serverUriBase); _serviceHost.Open(); _reconectionTimer = new Timer(new TimerCallback(VerifyClientConnections), null, 0, 30000); } catch (Exception ex) { SystemMonitor.Error("Failed to initialize service host [" + ex.Message + "]"); return(false); } } return(true); }
private void InitializeTaLibIndicators() { // Start init for ta lib indicators. Dictionary <string, MethodInfo> methodsVerified = new Dictionary <string, MethodInfo>(); lock (this) { // Setup the unstable period; unstable periods usually stretch to the start, however // we can approximate to 120 bars; this will extend the lookback of the unstable functions 120. // see here: http://www.tadoc.org/forum/index.php?topic=858.0 TicTacTec.TA.Library.Core.SetUnstablePeriod(TicTacTec.TA.Library.Core.FuncUnstId.FuncUnstAll, 120); MethodInfo[] methods = typeof(TicTacTec.TA.Library.Core).GetMethods(); foreach (MethodInfo methodInfo in methods) { if (methodInfo.ReturnType == typeof(Core.RetCode)) { if (methodsVerified.ContainsKey(methodInfo.Name)) {// Establish the double[] input baseMethod of the two and use that. ParameterInfo[] parameters = methodsVerified[methodInfo.Name].GetParameters(); ParameterInfo[] newParameters = methodInfo.GetParameters(); SystemMonitor.CheckThrow(parameters.Length == newParameters.Length); for (int i = 0; i < parameters.Length; i++) { if (newParameters[i].ParameterType == typeof(Single[]) && parameters[i].ParameterType == typeof(Double[])) {// Current is double version of the function, new is single, stop parameter check. break; } if (newParameters[i].ParameterType == typeof(Double[]) && parameters[i].ParameterType == typeof(Single[])) {// Current is single version of the function, new is double, swap and stop parameter check. methodsVerified[methodInfo.Name] = methodInfo; break; } } } else { methodsVerified.Add(methodInfo.Name, methodInfo); } } } } _indicatorsGroups.Add(IndicatorGroup.TaLib, new Dictionary <string, PlatformIndicator>()); // List here dataDelivery for all the indicators that are to be imported from TaLIB. #region Group TALin InitializeTaLibIndicator(methodsVerified["Acos"], "Vector Trigonometric ACos", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Ad"], "Chaikin A/D Line", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["Add"], "Vector Arithmetic Add", null, null, null, null, DataBar.DataValueEnum.Open, DataBar.DataValueEnum.Close); InitializeTaLibIndicator(methodsVerified["AdOsc"], "Chaikin A/D Oscillator", null, null, null, null, null, null, 10, 20); InitializeTaLibIndicator(methodsVerified["Adx"], "Average Directional Movement Index", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Adxr"], "Average Directional Movement Index Rating", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Apo"], "Absolute Price Oscillator", null, null, null, null, DataBar.DataValueEnum.Close, null, 10, 20, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["Aroon"], "Aroon", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["AroonOsc"], "Aroon Oscillator", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Asin"], "Vector Trigonometric ASin", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Atan"], "Vector Trigonometric ATan", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Atr"], "Average True Range", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["AvgPrice"], "Average Price", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["Bbands"], "Bollinger Bands", null, null, null, null, DataBar.DataValueEnum.Close, null, 14, 10d, 10d, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["Beta"], "Beta", null, null, null, null, DataBar.DataValueEnum.Open, DataBar.DataValueEnum.Close, 14); InitializeTaLibIndicator(methodsVerified["Bop"], "Balance Of Power", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["Cci"], "Commodity Channel Index", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Ceil"], "Vector Ceil", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Cmo"], "Chande Momentum Oscillator", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Correl"], "Pearson's Correlation Coefficient (r)", null, null, null, null, DataBar.DataValueEnum.Open, DataBar.DataValueEnum.Close, 14); InitializeTaLibIndicator(methodsVerified["Cos"], "Vector Trigonometric Cos", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Cosh"], "Vector Trigonometric Cosh", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Dema"], "Double Exponential Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Div"], "Vector Arithmetic Div", null, null, null, null, DataBar.DataValueEnum.Open, DataBar.DataValueEnum.Close); InitializeTaLibIndicator(methodsVerified["Dx"], "Directional Movement Index", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Ema"], "Exponential Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Exp"], "Vector Arithmetic Exp", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Floor"], "Vector Floor", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["HtDcPeriod"], "Hilbert Transform - Dominant Cycle Period", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["HtDcPhase"], "Hilbert Transform - Dominant Cycle Phase", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["HtPhasor"], "Hilbert Transform - Phasor Components", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["HtSine"], "Hilbert Transform - SineWave", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["HtTrendline"], "Hilbert Transform - Instantaneous Trendline", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["HtTrendMode"], "Hilbert Transform - Trend vs Cycle Mode", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Kama"], "Kaufman Adaptive Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["LinearReg"], "Linear Regression", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["LinearRegAngle"], "Linear Regression Angle", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["LinearRegIntercept"], "Linear Regression Intercept", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["LinearRegSlope"], "Linear Regression Slope", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Ln"], "Vector Log Natural", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Log10"], "Vector Log10", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Macd"], "Moving Average Convergence/Divergence", null, null, null, null, DataBar.DataValueEnum.Close, null, 10, 20, 12); InitializeTaLibIndicator(methodsVerified["MacdExt"], "MACD with controllable MA type", null, null, null, null, DataBar.DataValueEnum.Close, null, 10, Core.MAType.Ema, 20, Core.MAType.Ema, 12, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["MacdFix"], "Moving Average Convergence/Divergence Fix 12/26", null, null, null, null, DataBar.DataValueEnum.Close, null, 10); InitializeTaLibIndicator(methodsVerified["Mama"], "MESA Adaptive Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 10d, 20d); InitializeTaLibIndicator(methodsVerified["Max"], "Highest value over a specified period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MaxIndex"], "Index of highest value over a specified period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MedPrice"], "Median Price", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["Mfi"], "Money Flow Index", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["MidPoint"], "MidPoint over period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MidPrice"], "Midpoint Price over period", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Min"], "Lowest value over a specified period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MinIndex"], "Index of lowest value over a specified period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MinMax"], "Lowest and highest values over a specified period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MinMaxIndex"], "Indexes of lowest and highest values over a specified period", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MinusDI"], "Minus Directional Indicator", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["MinusDM"], "Minus Directional Movement", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Mom"], "Momentum", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["MovingAverage"], "Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14, Core.MAType.Sma); // Consumes double[] inPeriods, which is to be established programatically only. //InitializeTaLibIndicator(methodsVerified["MovingAverageVariablePeriod"], "Moving Average with variable period", null, null, 2, 20, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["Mult"], "Vector Arithmetic Mult", null, null, null, null, DataBar.DataValueEnum.Open, DataBar.DataValueEnum.Close); InitializeTaLibIndicator(methodsVerified["Natr"], "Normalized Average True Range", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Obv"], "On Balance Volume", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["PlusDI"], "Plus Directional Indicator", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["PlusDM"], "Plus Directional Movement", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Ppo"], "Percentage Price Oscillator", null, null, null, null, DataBar.DataValueEnum.Close, null, 12, 24, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["Roc"], "Rate of change : ((price/prevPrice)-1)*100", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["RocP"], "Rate of change Percentage: (price-prevPrice)/prevPrice", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["RocR"], "Rate of change ratio: (price/prevPrice)", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["RocR100"], "Rate of change ratio 100 scale: (price/prevPrice)*100", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); Indicator indicator = InitializeTaLibIndicator(methodsVerified["Rsi"], "Relative Strength Index", null, null, 0, 100, DataBar.DataValueEnum.Close, null, 14); indicator.Parameters.SetDynamic(PlatformIndicatorChartSeries.FixedLinePrefix + "High", 70); indicator.Parameters.SetDynamic(PlatformIndicatorChartSeries.FixedLinePrefix + "Low", 30); InitializeTaLibIndicator(methodsVerified["Sar"], "Parabolic SAR", null, null, null, null, null, null, 1d, 2d); InitializeTaLibIndicator(methodsVerified["SarExt"], "Parabolic SAR - Extended", null, null, null, null, null, null, 1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d); InitializeTaLibIndicator(methodsVerified["Sin"], "Vector Trigonometric Sin", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Sinh"], "Vector Trigonometric Sinh", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Sma"], "Simple Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Sqrt"], "Vector Square Root", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["StdDev"], "Standard Deviation", null, null, null, null, DataBar.DataValueEnum.Close, null, 14, 2d); InitializeTaLibIndicator(methodsVerified["Stoch"], "Stochastic", null, null, null, null, null, null, 10, 20, Core.MAType.Ema, 22, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["StochF"], "Stochastic Fast", null, null, null, null, null, null, 10, 20, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["StochRsi"], "Stochastic Relative Strength Index", null, null, null, null, DataBar.DataValueEnum.Close, null, 14, 10, 20, Core.MAType.Ema); InitializeTaLibIndicator(methodsVerified["Sub"], "Vector Arithmetic Substraction", null, null, null, null, DataBar.DataValueEnum.Open, DataBar.DataValueEnum.Close); InitializeTaLibIndicator(methodsVerified["Sum"], "Summation", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["T3"], "Triple Exponential Moving Average (T3)", null, null, null, null, DataBar.DataValueEnum.Close, null, 14, 2d); InitializeTaLibIndicator(methodsVerified["Tan"], "Vector Trigonometric Tan", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Tanh"], "Vector Trigonometric Tanh", null, null, null, null, DataBar.DataValueEnum.Close, null); InitializeTaLibIndicator(methodsVerified["Tema"], "Triple Exponential Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Trima"], "Triangular Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["Trix"], "1-day Rate-Of-Change (ROC) of a Triple Smooth EMA", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["TrueRange"], "True Range", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["Tsf"], "Time Series Forecast", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); InitializeTaLibIndicator(methodsVerified["TypPrice"], "Typical Price", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["UltOsc"], "Ultimate Oscillator", null, null, null, null, null, null, 12, 14, 16); InitializeTaLibIndicator(methodsVerified["Variance"], "Variance", null, null, null, null, DataBar.DataValueEnum.Close, null, 14, 2d); InitializeTaLibIndicator(methodsVerified["WclPrice"], "Weighted Close Price", null, null, null, null, null, null); InitializeTaLibIndicator(methodsVerified["WillR"], "Williams' %R", null, null, null, null, null, null, 14); InitializeTaLibIndicator(methodsVerified["Wma"], "Weighted Moving Average", null, null, null, null, DataBar.DataValueEnum.Close, null, 14); #endregion }
/// <summary> /// This allows more specific control over the operation. /// </summary> public bool Submit(OrderTypeEnum orderType, int volume, decimal?allowedSlippage, decimal?desiredPrice, decimal?takeProfit, decimal?stopLoss, string comment, out string operationResultMessage) { SystemMonitor.CheckThrow(volume > 0, "Misuse of the Order class."); if (State != OrderStateEnum.Initialized) { operationResultMessage = "Misuse of the Order class [Order not initialized; or Must not place trade, that has already been placed]."; SystemMonitor.Warning(operationResultMessage); return(false); } ISourceOrderExecution executionProvider = _executionProvider; operationResultMessage = "Session not assigned."; if (desiredPrice.HasValue == false) { desiredPrice = OrderInfo.TypeIsBuy(orderType) ? QuoteProvider.Bid : QuoteProvider.Ask; } if (executionProvider == null) {// Placement of order failed. State = OrderStateEnum.Failed; SystemMonitor.Report("Order was not executed [" + operationResultMessage + "]."); return(false); } string id = OrderExecutionProvider.SubmitOrder(Account.Info, this, Symbol, orderType, volume, allowedSlippage, desiredPrice, takeProfit, stopLoss, comment, out operationResultMessage); if (string.IsNullOrEmpty(id)) { State = OrderStateEnum.Failed; SystemMonitor.OperationError("Order was not executed [" + operationResultMessage + "]."); return(false); } lock (this) { _info.Type = orderType; _initialVolume = volume; _info.Id = id; _info.Volume = volume; _info.StopLoss = stopLoss; _info.TakeProfit = takeProfit; State = OrderStateEnum.Submitted; _localOpenTime = DateTime.Now; } Account.TradeEntities.AddOrder(this); if (State == OrderStateEnum.Executed) { RaiseOrderUpdatedEvent(UpdateTypeEnum.Executed); } else { RaiseOrderUpdatedEvent(UpdateTypeEnum.Submitted); } return(true); }
protected override bool OnInitialize(Platform platform) { TracerHelper.TraceEntry(); if (base.OnInitialize(platform) == false) { return(false); } string expertName = this.Name + ".expert"; // Clean expertname since we might be sending it trough command line. expertName = expertName.Replace(" ", "_"); expertName = expertName.Replace("\"", ""); lock (this) { if (_expert == null) {// Create the expert. SystemMonitor.CheckThrow(_expertType.IsSubclassOf(typeof(Expert)), "Invalid expert type passed in."); ConstructorInfo constructor = _expertType.GetConstructor(new Type[] { typeof(ISourceAndExpertSessionManager), typeof(string) }); if (constructor == null) {// Try the second option for construction. constructor = _expertType.GetConstructor(new Type[] { typeof(ISourceAndExpertSessionManager) }); } if (constructor == null) { SystemMonitor.Error("Failed to find corresponding constructor for expert type [" + _expertType.ToString() + "]."); return(false); } if (constructor.GetParameters().Length == 2) { _expert = (Expert)constructor.Invoke(new object[] { this, expertName }); } else { _expert = (Expert)constructor.Invoke(new object[] { this }); } } if (_expert.Initialize() == false) { SystemMonitor.Error("Expert host failed to connect to platform."); return(false); } if (_expert != null) { _expert.PersistenceDataUpdateEvent += new Expert.ExpertUpdateDelegate(_expert_PersistenceDataUpdateEvent); } } foreach (PlatformExpertSession session in SessionsArray) { if (session.Initialize(null) == false) { SystemMonitor.OperationWarning("Failed to initialize session."); } } ChangeOperationalState(OperationalStateEnum.Operational); TracerHelper.TraceExit(); return(true); }
public virtual bool Initialize(CustomObjectsManager manager) { SystemMonitor.CheckThrow(_manager == null); _manager = manager; return(true); }
/// <summary> /// The initialization of a platform consumes 2 main dataDelivery sources. /// The settings is used for primary, startup information (like where /// is the persistence DB file etc.) and the information inside the /// persistence is than on used to create components etc. /// </summary> public bool Initialize(PlatformSettings platformSettings) { TracerHelper.TraceEntry(); SystemMonitor.CheckThrow(_settings == null, "Platform already initialized."); lock (this) { _settings = platformSettings; if (_persistenceHelper == null) { _persistenceHelper = CreatePersistenceHelper(platformSettings); } } if (_persistenceHelper == null) { return(false); } LoadModules(_settings); if (_persistenceHelper.Count <Platform>(new MatchExpression("Name", this.Name)) == 0) {// This is a new platform. lock (this) { _guid = Guid.NewGuid(); } if (_persistenceHelper.Insert <Platform>(this, null) == false) { SystemMonitor.Error("Failed to persist new platform [" + this.Name + "]"); return(false); } } else {// This is existing. // Now try to load self from persistance storage. bool selectionResult = _persistenceHelper.SelectScalar <Platform>(this, new MatchExpression("Name", this.Name)); if (selectionResult == false) {// Failed to load self from DB. return(false); } } lock (this) { if (_serializationData.ContainsValue("diagnosticsMode")) { _settings.DiagnosticsMode = _serializationData.GetBoolean("diagnosticsMode"); } if (_serializationData.ContainsValue("uiSerializationInfo")) { // The main serialization dataDelivery stores the UI orderInfo. _uiSerializationInfo = _serializationData.GetValue <SerializationInfoEx>("uiSerializationInfo"); } if (_serializationData.ContainsValue("componentSpecificSerializationInfo")) { // The main serialization dataDelivery stores the UI orderInfo. _componentSpecificSerializationInfo = _serializationData.GetValue <SerializationInfoEx>("componentSpecificSerializationInfo"); } } //_server = new Arbiter.TransportIntegrationServer(_platformUri); //Arbiter.AddClient(_server); GeneralHelper.FireAndForget(delegate() {// LoadFromFile components. // Registering of components is better done outside the lock, // since components may launch requests to platform at initializations. _isLoading = true; // Components are stored in the PlatformComponents database, they are being serialized and the entire object is // persisted in the DB, as well as the type information for it and a reference to the platform instance it belongs to. List <long> failedSerializationsIds = new List <long>(); List <PlatformComponent> components = PersistenceHelper.SelectSerializedType <PlatformComponent>( new MatchExpression("PlatformId", this.Id), "Data", null, failedSerializationsIds); SortedList <int, List <PlatformComponent> > componentsByLevel = GetComponentsByLevel(components); GatherMandatoryComponents(componentsByLevel); foreach (int level in componentsByLevel.Keys) {// Register lower level components first. foreach (PlatformComponent component in componentsByLevel[level]) { if (DoRegisterComponent(component, true) == false && component.Id.HasValue && ComponentDeserializationFailedEvent != null) { ComponentDeserializationFailedEvent(component.Id.Value, component.GetType().Name); } } } // Handle failed deserializations. foreach (int id in failedSerializationsIds) { string typeName = "Unknown"; try {// Extract the type of this entry. List <object[]> result = _persistenceHelper.SelectColumns <PlatformComponent>( new MatchExpression("Id", id), new string[] { "Type" }, 1); Type type = Type.GetType(result[0][0].ToString()); if (type != null) { typeName = type.Name; } } catch (Exception ex) { SystemMonitor.Error("Failed to extract type information [" + ex.Message + "]."); } if (ComponentDeserializationFailedEvent != null) { ComponentDeserializationFailedEvent(id, typeName); } } _isLoading = false; }); return(true); }
/// <summary> /// Constructor. /// </summary> public ArbiterSlimExecutionStrategy(ArbiterSlimActiveClientStub client) { SystemMonitor.CheckThrow(client != null, "Client not assigned to execution strategy."); _client = client; }
public void Initialize(ChartPane pane) { SystemMonitor.CheckThrow(_pane == null); _pane = pane; }