public DistributorService(IRepository repository, IBroker windowsPhoneBroker) { _repository = repository; _windowsPhoneBroker = windowsPhoneBroker; _repository.PivotAffected += Repository_PivotAffected; _messageBus = new MessageBus(); }
public ControllerEngine(bool startSynchronization, int syncFrequency) { _JobManager = new JobManager(); _Broker = new Broker(); _PluginThreadBlocker = new AutoResetEvent(false); IsDisposed = false; _ShouldRunPlugins = startSynchronization; _PluginThread = new Thread(CheckAllPluginsAndRunRunablesLoop); _PluginThread.Name = "Controller Thread"; JobManager.JobAddedToQueue += JobManager_JobAddedToQueue; Broker.ExecuteCompleted += Broker_PluginOperationEnded; Broker.ExecuteFailed += Broker_PluginOperationEnded; Broker.CommitCompleted += Broker_PluginOperationEnded; Broker.CommitFailed += Broker_PluginOperationEnded; Broker.RollbackCompleted += Broker_PluginOperationEnded; Broker.RollbackFailed += Broker_PluginOperationEnded; InitializeAgents(); if (startSynchronization) _JobManager.BeginSynchronize(syncFrequency); }
public Heartbeat(ServiceHostBase host, IBroker broker) { _broker = broker; _host = host; HeartbeatInterval = TimeSpan.FromSeconds(1); _heartbeatStream = Observable.Timer(TimeSpan.Zero, HeartbeatInterval); }
protected PublishJob(IBroker broker, Exchange exchange, String routingKey) { Broker = broker; _exchange = exchange; _routingKey = routingKey; _stopwatch = new Stopwatch(); }
private static void RunOn(IBroker broker, Int32 times, Int32 count, TextWriter writer) { var exchange = DeclareExchange(broker); var queue = BindQueue(broker, "test_benchmarks_queue", exchange); var durableExchange = DeclareDurableExchange(broker); var durableQueue = BindDurableQueue(broker, "test_benchmarks_durable_queue", durableExchange); var jobs = new IJob[] { new DurableMessagesPublishJob(broker, durableExchange, RoutingKey), new ConsumingJob(broker, durableQueue) }.Repeat(times) .Concat(new IJob[] { new NonDurableMessagesPublishJob(broker, exchange, RoutingKey), new ConsumingJob(broker, queue) }.Repeat(times)); foreach (var job in jobs) { GC.Collect(); GC.Collect(); job.RunAsync(count).Result.Print(writer); } }
public void Stop() { Stopping = true; _tokenSource.Cancel(); _broker = null; Stopping = false; Stopped = true; }
public BlotterServiceHost(IBlotterService service, IBroker broker) : base(broker, "blotter") { _service = service; _broker = broker; RegisterCall("getTradesStream", GetTradesStream); StartHeartBeat(); }
public override void Init(Object o) { SiteDTO dto = o as SiteDTO; siteName = dto.Name; brokerSite = new BrokerSiteFrontEnd(dto.Brokers, dto.Name); Console.Write(brokerSite.ToString()); Console.WriteLine("Publisher Up and running........"); }
public OrderSplitService(IBroker broker1, IBroker broker2) { if (broker1 == null) throw new ArgumentNullException("broker1"); if (broker2 == null) throw new ArgumentNullException("broker2"); _broker1 = broker1; _broker2 = broker2; }
public Portfolio( double cash, IBroker broker, TradingLog tradingLog ) { myCash = cash; myBroker = broker; myTradingLog = tradingLog; myQuantity = 0; }
public ReferenceWriteServiceHost(ReferenceWriteService service, IBroker broker) : base(broker, "reference") { _service = service; RegisterCall(ActivateCurrencyPairProcedureName, ActivateCurrencyPair); RegisterCall(DeactivateCurrencyPairProcedureName, DeactivateCurrencyPair); StartHeartBeat(); }
public PricingServiceHost(IPricingService service, IBroker broker) : base(broker, "pricing") { _service = service; _broker = broker; RegisterCall("getPriceUpdates", GetPriceUpdates); StartHeartBeat(); StartPricePublisher(); }
//private Dictionary<string, Event> eventsReceived; public Subscriber(string name, string url, string brokerUrl, IBroker broker) { this.name = name; this.adress = url; this.brokerUrl = brokerUrl; this.broker = broker; this.eventsReceived = new List<KeyValuePair<string, Event>>(); this.frozenEvents = new List<FrozenEvent>(); }
public Subscription(string queueName) { _queueName = queueName; _broker = ObjectFactory.GetInstance<Broker>() as IBroker; _tokenSource = new CancellationTokenSource(); _brokerCancelToken = _tokenSource.Token; _brokerCancelToken.Register(_broker.Stop); _brokerTask = new Task(() => _broker.Start(_queueName), _brokerCancelToken); }
public AnalyticsServiceHost(IAnalyticsService service, IBroker broker, TradeCache tradeCache) : base(broker, "analytics") { _service = service; _broker = broker; _tradeCache = tradeCache; _subscriptions = new CompositeDisposable(); RegisterCall("getAnalytics", GetAnalyticsStream); StartHeartBeat(); ListenForPricesAndTrades(); }
public void TestInitialize() { _broker1 = new Broker1(); _broker2 = new Broker2(); var orderSplitService = new OrderSplitService(_broker1, _broker2); _orderRepository = new InMemoryOrderRepository(); _orderExecutionService = new OrderExecutionService(orderSplitService, _orderRepository); _clientA = new Client(Guid.NewGuid(), "ClientA"); _clientB = new Client(Guid.NewGuid(), "ClientB"); _clientC = new Client(Guid.NewGuid(), "ClientC"); }
public ForumService(IForumRepository forumRepository, ITopicRepository topicRepository, IPostRepository postRepository, ICategoryRepository categoryRepository, IProfileRepository profileRepository, ITextParsingService textParsingService, ISettingsManager settingsManager, ILastReadService lastReadService, IEventPublisher eventPublisher, IBroker broker) { _forumRepository = forumRepository; _topicRepository = topicRepository; _postRepository = postRepository; _categoryRepository = categoryRepository; _profileRepository = profileRepository; _settingsManager = settingsManager; _textParsingService = textParsingService; _lastReadService = lastReadService; _eventPublisher = eventPublisher; _broker = broker; }
public Deal(IBroker broker, decimal amount, decimal rate, decimal commission) { if (broker == null) throw new ArgumentNullException("broker"); Broker = broker; Amount = amount; Rate = rate; Commission = commission; CostWithoutCommission = amount * rate; CommissionCost = CostWithoutCommission * commission; TotalCost = CostWithoutCommission + CommissionCost; }
public TopicService(IForumRepository forumRepository, ITopicRepository topicRepository, IPostRepository postRepository, IProfileRepository profileRepository, ITextParsingService textParsingService, ISettingsManager settingsManager, ISubscribedTopicsService subscribedTopicsService, IModerationLogService moderationLogService, IForumService forumService, IEventPublisher eventPublisher, IBroker broker, ISearchRepository searchRepository, IUserRepository userRepository) { _forumRepository = forumRepository; _topicRepository = topicRepository; _postRepository = postRepository; _profileRepository = profileRepository; _settingsManager = settingsManager; _textParsingService = textParsingService; _subscribedTopicService = subscribedTopicsService; _moderationLogService = moderationLogService; _forumService = forumService; _eventPublisher = eventPublisher; _broker = broker; _searchRepository = searchRepository; _userRepository = userRepository; }
public void RegisterBroker(IBroker broker) { if (broker == null) { throw new ArgumentNullException("broker"); } if (_registeredBrokers.Count == 2) { throw new ApplicationException("Service constrained to 2 brokers"); } _registeredBrokers.Add(broker); if (_registeredBrokers.Count == 2) { _isServiceInProperState = true; } }
public static void CLRMain(IBroker b) { Console.WriteLine("running inside CLR"); Console.WriteLine("b: " + b.FullName); Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location)); foreach (var item in AppDomain.CurrentDomain.GetAssemblies()) { Console.WriteLine(Path.GetFullPath(item.Location) + " types: " + item.GetTypes().Length); } // if jsc supported pdb rewrite we could have a break point over here! MessageBox.Show("hello"); Console.WriteLine("done!"); }
public BrokerLogic(IBroker myProxy,string name, string orderingPolicy, string routingPolicy, string loggingLevel, string pmLogServerUrl) { this.remoteProxy = myProxy; this.brokerName = name; this.pmLogServerUrl = pmLogServerUrl; this.orderingPolicy = orderingPolicy; this.loggingLevel = loggingLevel; this.routingPolicy = routingPolicy; if (routingPolicy.Equals("filter")) { this.router = new Filtered(this); } else if (routingPolicy.Equals("flooding")) { this.router = new Flooding(this); } if (orderingPolicy.Equals("FIFO")) { this.order = new FifoOrdering(); } else if (orderingPolicy.Equals("NO")) { this.order = new NoOrdering(); } else if (orderingPolicy.Equals("TOTAL")) { this.order = new TotalOrdering(this); } if (orderingPolicy.Equals("TOTAL")) { this.pool = new CommonTypes.ThreadPool(1); } else { this.pool = new CommonTypes.ThreadPool(10); } this.topicSubscribers = new TopicSubscriberCollection(); childSites = new Dictionary<string, IBroker>(); }
public void HostModule(string interfaceName, ModMod mod, IBroker b) { Type iface = null; if (ModInterfaces.ContainsKey(interfaceName)) { iface = ModInterfaces[interfaceName]; } else if (ModLocalInterfaces.ContainsKey(interfaceName)) { iface = ModLocalInterfaces[interfaceName]; } else { logger.Error("the module at {0} not found", interfaceName); return; // error } var tc = typeof(IModConsumer); mod.Role = tc.IsAssignableFrom(iface) ? ExecutionType.Consumer : ExecutionType.Producer; mod.MI = (IMod)Activator.CreateInstance(iface); mod.ModAssembly = loadedInterfaces[interfaceName]; if (Modules.ContainsKey(mod.UniqueName)) { logger.Error("the module: {0} at {1} already registered", mod.UniqueName, interfaceName); return; } Modules.Add(mod.UniqueName, mod); // TODO: Extract to broker context mod.MI.Initialise(b, mod); MetaTask[] tasks = mod.MI.RegisterTasks(mod); if (tasks != null) foreach (MetaTask t in tasks) { b.RegisterTempTask(t, mod); } }
public PricePublisher(IObservable<SpotPriceDto> priceStream, IBroker broker) { _priceStream = priceStream; _broker = broker; }
// Public specific methods public override void Init(Object o) { SiteDTO siteDto = o as SiteDTO; brokerSite = new BrokerSiteFrontEnd(siteDto.Brokers, siteDto.Name); Console.Write(brokerSite.ToString()); Console.WriteLine("Subscriber up and running........"); }
public CommandsTests() { _broker = FakeIoCSetup.GetBroker(); }
public ConcurrentDictionaryRepository(ILogger logger = null, IBroker broker = null) : base(logger, broker) { store = new Lazy <ConcurrentDictionary <TId, T> >(StoreFactory); }
public void SetTrades(List <Trade> trades, ITradeDetailsAutoCalculatorService tradeCalculateService, IBroker broker) { AccountLastUpdated = DateTime.UtcNow; foreach (var t in Trades) { tradeCalculateService.RemoveTrade(t); } Trades.Clear(); Trades.AddRange(trades); Log.Debug($"Completed updating {broker.Name} trades"); _brokerAccountUpdatedSubject.OnNext(new BrokerAccountUpdated(this)); }
// IEOD - with Only LTP files (and no re-run) algo public void RunAlgos(object obj) { int symbolCounter = 0; var sts = new List <SymbolTick>(10000); // Get algo data var brokerAccountObj = (BrokingAccountObject)obj; IBroker broker = brokerAccountObj.Broker; var algoMetadata = (AlgoMetadata)brokerAccountObj.CustomData; AddTickChartDelegate dataDelegate = algoMetadata.DataDelegate; var chartDelegate = algoMetadata.ChartDelegate; var logDelegate = algoMetadata.LogDelegate; var tickMetaData = algoMetadata.TickMetadata; string r1, r2; var isForceUpdate = algoMetadata.IsForceUpdate; var algoParams = algoMetadata.AlgoParams; var AlgoIdSet = AlgoIds; if (DoAllAlgos) { short minAlgo = 10; short maxAlgo = 160; AlgoIdSet = new short[maxAlgo - minAlgo + 1]; for (short i = minAlgo; i <= maxAlgo; i++) { AlgoIdSet[i - minAlgo] = i; } //AlgoIdSet[maxAlgo - minAlgo + 1] = 1; } // Go for each symbol foreach (var tmd in tickMetaData) { r1 = tmd.R1; r2 = tmd.R2; var symbol = tmd.Symbol; var tickFileName = tmd.Path; logDelegate(string.Format("Thread {0}: Time: {4} Starting Stock: {1} r1: {2} r2: {3}\n", Thread.CurrentThread.ManagedThreadId, symbol, r1, r2, DateTime.Now)); // CHECK TICKFILE EXISTS if (!File.Exists(tickFileName)) { Logger.LogWarningMessage(string.Format("TickFile {0} not found.", tickFileName)); continue; } // Check if ALGO results already exist (or need to be overwritten) PERIODWISE (r1, r2 combo).Checking last mktDir // If this goes past then it means need to run at least 1 mktDirPerc if (!isForceUpdate) { bool doesEOPExist = true; foreach (var algoId in AlgoIdSet) { if (GetAlgo(algoId, algoParams.Clone(), true) == null) { continue; } // if trader run is already present for this symbol, then just move to next symbol doesEOPExist = doesEOPExist && EOPTradeStats.DoesExistEOPStatsForMinMaxAlgos(symbol, algoId, MktDirectionParams[MktDirectionParams.Length - 1], r1, r2); if (!doesEOPExist) { break; } } if (doesEOPExist) { continue; } } ++symbolCounter; sts.Clear(); GC.Collect(); // Go through Each day's data for given symbol logDelegate(string.Format("Thread {0}: Stock: {1} " + "Time: {2} , Reading tickfile\n", Thread.CurrentThread.ManagedThreadId, symbol, DateTime.Now)); Dictionary <int, Dictionary <int, SymbolTick> > TicksCall = new Dictionary <int, Dictionary <int, SymbolTick> >(10); Dictionary <int, Dictionary <int, SymbolTick> > TicksPut = new Dictionary <int, Dictionary <int, SymbolTick> >(10); DateTime expiryDate = DateTime.Now; int lotSize = 50; InstrumentType instrType = InstrumentType.OptionCallIndex; Instrument instr = null; if (algoParams.IsHedgeAlgo) { Dictionary <int, Dictionary <int, SymbolTick> > dict; //OPT-CNXBAN-26-Jul-2012-10500-CE-Q25-0915 var dir = Path.GetDirectoryName(tickFileName); var allTickFiles = Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories); var allSymbolOptFiles = Directory.EnumerateFiles(dir, "OPT-" + symbol + "*", SearchOption.AllDirectories); if (allSymbolOptFiles.Count() == 0) { continue; } foreach (string filePath in allTickFiles) { var fileName = Path.GetFileNameWithoutExtension(filePath); if (!fileName.StartsWith("OPT-" + symbol)) { continue; } var fileParts = fileName.Split('-'); expiryDate = DateTime.Parse(fileParts[2] + "-" + fileParts[3] + "-" + fileParts[4]); lotSize = int.Parse(fileParts[7].Replace("Q", "")); var strkPrc = int.Parse(fileParts[5]); if (fileParts[6] == "CE") { instrType = InstrumentType.OptionCallIndex; dict = TicksCall; } else { instrType = InstrumentType.OptionPutIndex; dict = TicksPut; } instr = new Instrument(symbol, instrType, strkPrc, expiryDate, lotSize); if (!dict.ContainsKey(strkPrc)) { dict.Add(strkPrc, new Dictionary <int, SymbolTick>(400)); } var prcStore = dict[strkPrc]; var arrOpt = File.ReadAllLines(filePath); int tickCnt = 0; foreach (var s in arrOpt) { var dqi = ParseTickString(s, tmd.TickFormatType); // Add to list of DQI if (dqi == null) { continue; } dqi.InstrumentType = instrType; dqi.UnderlyingSymbol = symbol; dqi.ExpiryDateTime = expiryDate; dqi.StrikePriceDouble = strkPrc; var si = new SymbolTick(true); si.D.Q = dqi; si.I = instr; tickCnt++; var datetime = si.D.Q.QuoteTime; int time = datetime.Hour * 100 + datetime.Minute; if (!prcStore.ContainsKey(time)) { prcStore.Add(time, si); } } } } // READ TICKFILE var arr = File.ReadAllLines(tickFileName); double ltp = 0; int tickCount = 0; instrType = InstrumentType.FutureIndex; instr = new Instrument(symbol, instrType, 0, expiryDate, lotSize); foreach (var s in arr) { var dqi = ParseTickString(s, tmd.TickFormatType); // Add to list of DQI if (dqi == null) { continue; } dqi.InstrumentType = instrType; dqi.UnderlyingSymbol = symbol; dqi.ExpiryDateTime = expiryDate; // Add only stablemarket ticks, i.e. after inital 5 minutes. Start from 10 AM for stable data //if (MarketUtils.IsTimeAfter10AM(dqi.UpdateTime)) { var si = new SymbolTick(true); si.D.Q = dqi; si.I = instr; sts.Add(si); ltp += dqi.LastTradedPriceDouble; tickCount++; } } // Derive the quantity for FNO int qty = 1; double avgLotValue = 300000; if (tickCount != 0 && ltp != 0) { ltp = ltp / tickCount; qty = (int)Math.Round(avgLotValue / ltp); } foreach (var algoId in AlgoIdSet) { if (GetAlgo(algoId, algoParams.Clone(), true) == null) { continue; } // This is ALGO wise check. (for a given symbol, r1, r2) Check by last mktDirPerc if (!isForceUpdate) { // if trader run is already present for this symbol, then just move to next symbol var doesEOPExist = EOPTradeStats.DoesExistEOPStatsForMinMaxAlgos(symbol, algoId, MktDirectionParams[MktDirectionParams.Length - 1], r1, r2); if (doesEOPExist) { //Logger.LogWarningMessage( // string.Format( // "EOP TradeRun Stats for symbol={0}, algo={1} already exist. Skipping FULL symbol.", // symbol, algoId)); continue; } } foreach (var mktDirecparam in MktDirectionParams) { var percMarketDirectionChange = Math.Round(mktDirecparam, 2); // Special for 1 sec data //if (percMarketDirectionChange == 0.1)// || percMarketDirectionChange == 0.5) // if (!(symbol == "NIFTY" || symbol == "DEFTY" || symbol == "SENSEX")) // continue; // MktDirPerc wise check for a given symbol, algo, r1 and r2 if (!isForceUpdate) { // if trader run is already present for this symbol, then just move to next symbol bool doesEOPExist = EOPTradeStats.DoesExistEOPStatsForMinMaxAlgos(symbol, algoId, percMarketDirectionChange, r1, r2); if (doesEOPExist) { //Logger.LogWarningMessage( // string.Format( // "EOP TradeRun Stats for symbol={0}, algo={1}, marketDirection={2} already exist. Skipping for this combination.", // symbol, algoId, percMarketDirectionChange)); continue; } } logDelegate(string.Format("Thread {0} Time {1} ~ Stock: {2}, R1: {3}, Running {4} @ {5}%\n", Thread.CurrentThread.ManagedThreadId, DateTime.Now, symbol, r1, algoId, percMarketDirectionChange)); // RUN ALGO var algoParamsClone = algoParams.Clone(); algoParamsClone.PercMarketDirectionChange = percMarketDirectionChange; algoParamsClone.AlgoId = algoId; algoParamsClone.R1 = r1; algoParamsClone.R2 = r2; if (symbol.Contains("OPT-")) { algoParamsClone.I = new Instrument(symbol, InstrumentType.OptionCallIndex, ltp, new DateTime(2013, 03, 28), 50); } else { algoParamsClone.I = new Instrument(symbol, InstrumentType.FutureStock, 100, new DateTime(2013, 03, 28), qty); } algoParamsClone.PositionsFile = SystemUtils.GetStockRunTempFileName("Positions-" + algoParamsClone.Description()); algoParamsClone.StateFile = SystemUtils.GetStockRunTempFileName("AlgoState-" + algoParamsClone.Description()); TradingAlgo algo = GetAlgo(algoId, algoParamsClone, false); algo.Prolog(); if (algoParams.IsHedgeAlgo) { algo.S.TicksCall = TicksCall; algo.S.TicksPut = TicksPut; } //int tickCntr1Min = 0; // Run for each quote tick now out of all collected from the replay file foreach (var st in sts) { //if (!MarketUtils.IsTimeAfter10AM(dqi.UpdateTime)) //{ // continue; //} //tickCntr1Min++; try { if (algo.DoStopAlgo) { logDelegate(string.Format("Thread {0}: Stock: {1} " + "Time: {2} , Coming out due to Stop loss/NumTrades for the day\n", Thread.CurrentThread.ManagedThreadId, symbol, DateTime.Now)); break; } //if (algo.AlgoParams.AlgoId >= 120 && algo.AlgoParams.AlgoId < 150) //{ // if (tickCntr1Min % 5 == 0) // { // algo.S.TotalTickCount++; // algo.AddTick(st); // } // continue; //} algo.S.TotalTickCount++; algo.AddTick(st); } catch (Exception ex) { FileTracing.TraceOut("Exception in algo.AddTick(): " + ex.Message + "\n" + ex.StackTrace); } algo.LTP = st.GetLTP(); } algo.Epilog(); //EventResetChart(null, null); // RESET Time in Ticks //foreach (var st in sts) // st.D.Q.UpdateTime = st.D.Q.QuoteTime; } // foreach algo param } // foreach algo } //foreach symbol logDelegate(string.Format("Thread {0} completed !! at Time: {1} \n", Thread.CurrentThread.ManagedThreadId, DateTime.Now)); }
/// <summary> /// Start code execution or backtest /// </summary> /// <param name="historicalData">Available historical data</param> /// <param name="selectedData">Historical data to use</param> /// <param name="accounts">Available accounts</param> /// <param name="portfolios">Available portfolios</param> /// <param name="state">Signal state to use for signal (Running or Backtesting)</param> public void Start(List <HistoricalData> historicalData, List <HistoricalData> selectedData, List <AccountInfo> accounts, SignalState state) { if (!selectedData.Any()) { RaiseOutput("Failed to start: selected data collection is empty"); return; } _prevExecution = DateTime.MinValue; _selectedData.AddRange(selectedData); _dataProvider = new DataProvider(historicalData); ((DataProvider)_dataProvider).NewBarAppended += OnNewBarAppended; try { var msc = DateTime.UtcNow; var success = Code.SetParameters(CodeParameters.Select(ToExternalCodeParameters).ToList()); if (!success) { RaiseOutput("Failed to set user code parameters"); return; } if (Code is IndicatorBase) { var indicator = Code as IndicatorBase; success = indicator.Init(ToCodeSelection(_selectedData[0]), _dataProvider); if (success) { var seconds = (DateTime.UtcNow - msc); var maxRecords = 0; if (indicator.Series.Count > 0) { indicator.Series.Select(series => series.Length).Max(); } RaiseOutput(String.Format(" *** Initialization: {0} series, {1} records, time: {2:0} ms{3}", indicator.Series.Count, maxRecords, seconds.TotalMilliseconds, Environment.NewLine)); } } else if (Code is SignalBase) { var signal = Code as SignalBase; _backtestProgress = -1; _broker = new SimulationBroker(accounts.Select(a => new SimulationAccount { Balance = a.Balance, Currency = a.Currency, ID = a.ID, Password = a.Password, UserName = a.UserName })); success = signal.Init(_broker, _dataProvider, _selectedData.Select(ToCodeSelection).ToList(), state, new StrategyParams(-1)); if (success) { var span = (DateTime.UtcNow - msc); RaiseOutput(String.Format(" *** Initialization time: {0:0} ms{1}", span.TotalMilliseconds, Environment.NewLine)); _tmrBacktestStatusCheck.Start(); if (state == SignalState.Running) { _tmrPeriodicExecution.Start(); } else if (state == SignalState.Backtesting) { _backtestProgress = 0F; RaiseOutput(" > Starting backtest for " + signal.Name); signal.StartBacktest(new CommonObjects.BacktestSettings()); } } } if (!success) { RaiseOutput("Failed to initialize user code instance"); } } catch (Exception ex) { RaiseOutput(ex.ToString()); } }
public void InitialiseEntry(IBroker context, IBrokerModule thisModule) { MI.Initialise(context, thisModule); }
public void AddBroker( IBroker broker, int id ) { brokers.Add( broker ); ids.Add( id ); }
public CryptoTransactionsUSDTCalculator(IBrokersCandlesService candlesService, IBroker binanceBroker) { _candlesService = candlesService; _binanceBroker = binanceBroker; }
public MessageEvent(IBroker broker) { Broker = broker; }
public InMemoryConsumer(IBroker broker, IEndpoint endpoint) : base(broker, endpoint) { }
public InMemoryProducer(IBroker broker, IEndpoint endpoint, MessageKeyProvider messageKeyProvider, ILogger <Producer> logger, MessageLogger messageLogger) : base(broker, endpoint, messageKeyProvider, logger, messageLogger) { }
public NamedBroker(string name, IBroker bro) { this.name = name; this.broker = bro; }
public PostMasterService(ITextParsingService textParsingService, ITopicRepository topicRepository, IPostRepository postRepository, IForumRepository forumRepository, IProfileRepository profileRepository, IEventPublisher eventPublisher, IBroker broker, ISearchIndexQueueRepository searchIndexQueueRepository, ITenantService tenantService, ISubscribedTopicsService subscribedTopicsService, IModerationLogService moderationLogService, IForumPermissionService forumPermissionService, ISettingsManager settingsManager, ITopicViewCountService topicViewCountService) { _textParsingService = textParsingService; _topicRepository = topicRepository; _postRepository = postRepository; _forumRepository = forumRepository; _profileRepository = profileRepository; _eventPublisher = eventPublisher; _broker = broker; _searchIndexQueueRepository = searchIndexQueueRepository; _tenantService = tenantService; _subscribedTopicsService = subscribedTopicsService; _moderationLogService = moderationLogService; _forumPermissionService = forumPermissionService; _settingsManager = settingsManager; _topicViewCountService = topicViewCountService; }
public List <TickData> GetTickData(IBroker broker, string market, DateTime utcStart, DateTime utcEnd) { throw new NotImplementedException(); }
public static Order Sell(DateTime timestamp, double price, int quantity, IBroker broker) { double fee = broker.CalculateCommission(quantity, price); return(new Order(OrderType.Sell, timestamp, price, quantity, fee)); }
public MarkdownBodyTagHelper( IBroker broker) { _broker = broker; }
public BrokerTests() { //_service = new BrokerFake(); _service = new Broker("IOL", 0.005); }
public ConsumingJob(IBroker broker, Queue queue) { Broker = broker; _queue = queue; _stopwatch = new Stopwatch(); }
public void RecalculateTrade(Trade trade, IBrokersCandlesService candleService, IMarketDetailsService marketsService, IBroker broker) { // Update price per pip if (trade.EntryQuantity != null && trade.EntryDateTime != null) { trade.PricePerPip = candleService.GetGBPPerPip(marketsService, broker, trade.Market, trade.EntryQuantity.Value, trade.EntryDateTime.Value, true); } // Update risk if (trade.InitialStopInPips == null || trade.PricePerPip == null) { trade.RiskPercentOfBalance = null; trade.RiskAmount = null; trade.RiskPercentOfBalance = null; } else { trade.RiskAmount = trade.PricePerPip.Value * trade.InitialStopInPips.Value; var balance = GetBalance(trade.StartDateTime); if (balance != 0.0M) { var startTime = trade.OrderDateTime ?? trade.EntryDateTime; trade.RiskPercentOfBalance = (trade.RiskAmount * 100M) / GetBalance(startTime); } else { trade.RiskPercentOfBalance = null; } } }
public void SetBrokerForTest(IBroker broker) { OverloadBrokerForTest = broker; }
public static int Main(string[] args) { //Console.ReadLine(); Broker = new Broker(); CommandLineApplication app = new CommandLineApplication(false) { Name = "dotnet new3", FullName = "Template Instantiation Commands for .NET Core CLI." }; CommandArgument template = app.Argument("template", "The template to instantiate."); CommandOption listOnly = app.Option("-l|--list", "Lists templates with containing the specified name.", CommandOptionType.NoValue); CommandOption name = app.Option("-n|--name", "The name for the output. If no name is specified, the name of the current directory is used.", CommandOptionType.SingleValue); CommandOption dir = app.Option("-d|--dir", "Indicates whether to display create a directory for the generated content.", CommandOptionType.NoValue); CommandOption alias = app.Option("-a|--alias", "Creates an alias for the specified template", CommandOptionType.SingleValue); CommandOption parametersFiles = app.Option("-x|--extra-args", "Adds a parameters file.", CommandOptionType.MultipleValue); CommandOption install = app.Option("-i|--install", "Installs a source or a template pack.", CommandOptionType.MultipleValue); CommandOption uninstall = app.Option("-u|--uninstall", "Uninstalls a source", CommandOptionType.MultipleValue); CommandOption source = app.Option("-s|--source", "The specific template source to get the template from.", CommandOptionType.SingleValue); CommandOption currentConfig = app.Option("-c|--current-config", "Lists the currently installed components and sources.", CommandOptionType.NoValue); CommandOption help = app.Option("-h|--help", "Indicates whether to display the help for the template's parameters instead of creating it.", CommandOptionType.NoValue); CommandOption installComponent = app.Option("--install-component", "Installs a component.", CommandOptionType.MultipleValue); CommandOption resetConfig = app.Option("--reset", "Resets the component cache and installed template sources.", CommandOptionType.NoValue); CommandOption rescan = app.Option("--rescan", "Rebuilds the component cache.", CommandOptionType.NoValue); CommandOption global = app.Option("--global", "Performs the --install or --install-component operation for all users.", CommandOptionType.NoValue); CommandOption reinit = app.Option("--reinitialize", "Sets dotnet new3 back to its pre-first run state.", CommandOptionType.NoValue); CommandOption quiet = app.Option("--quiet", "Doesn't output any status information.", CommandOptionType.NoValue); CommandOption skipUpdateCheck = app.Option("--skip-update-check", "Don't check for updates.", CommandOptionType.NoValue); CommandOption update = app.Option("--update", "Update matching templates.", CommandOptionType.NoValue); app.OnExecute(() => { if (reinit.HasValue()) { Paths.FirstRunCookie.Delete(); return(Task.FromResult(0)); } if (!Paths.UserDir.Exists() || !Paths.FirstRunCookie.Exists()) { if (!quiet.HasValue()) { Reporter.Output.WriteLine("Getting things ready for first use..."); } if (!Paths.FirstRunCookie.Exists()) { PerformReset(true, true); Paths.FirstRunCookie.WriteAllText(""); } ConfigureEnvironment(); PerformReset(false, true); } if (rescan.HasValue()) { Broker.ComponentRegistry.ForceReinitialize(); ShowConfig(); return(Task.FromResult(0)); } if (resetConfig.HasValue()) { PerformReset(global.HasValue()); return(Task.FromResult(0)); } if (currentConfig.HasValue()) { ShowConfig(); return(Task.FromResult(0)); } if (install.HasValue()) { InstallPackage(install.Values, true, global.HasValue(), quiet.HasValue()); return(Task.FromResult(0)); } if (installComponent.HasValue()) { InstallPackage(installComponent.Values, false, global.HasValue(), quiet.HasValue()); return(Task.FromResult(0)); } if (update.HasValue()) { return(PerformUpdateAsync(template.Value, quiet.HasValue(), source)); } if (uninstall.HasValue()) { foreach (string value in uninstall.Values) { if (value == "*") { Paths.TemplateSourcesFile.Delete(); Paths.AliasesFile.Delete(); if (global.HasValue()) { Paths.GlobalTemplateCacheDir.Delete(); } else { Paths.TemplateCacheDir.Delete(); } return(Task.FromResult(0)); } if (!TryRemoveSource(value)) { string cacheDir = global.HasValue() ? Paths.GlobalTemplateCacheDir : Paths.TemplateCacheDir; bool anyRemoved = false; if (!value.Exists()) { foreach (string file in cacheDir.EnumerateFiles($"{value}.*.nupkg")) { int verStart = file.IndexOf(value, StringComparison.OrdinalIgnoreCase) + value.Length + 1; string ver = file.Substring(verStart); ver = ver.Substring(0, ver.Length - ".nupkg".Length); Version version; if (Version.TryParse(ver, out version)) { if (!quiet.HasValue()) { Reporter.Output.WriteLine($"Removing {value} version {version}..."); } anyRemoved = true; file.Delete(); } } } if (!anyRemoved && !quiet.HasValue()) { Reporter.Error.WriteLine($"Couldn't remove {value} as a template source.".Red().Bold()); } } } return(Task.FromResult(0)); } if (listOnly.HasValue()) { ListTemplates(template, source); return(Task.FromResult(0)); } IReadOnlyDictionary <string, string> parameters; try { parameters = app.ParseExtraArgs(parametersFiles); } catch (Exception ex) { Reporter.Error.WriteLine(ex.Message.Red().Bold()); app.ShowHelp(); return(Task.FromResult(-1)); } return(TemplateCreator.Instantiate(app, template.Value ?? "", name, dir, source, help, alias, parameters, quiet.HasValue(), skipUpdateCheck.HasValue())); }); int result; try { result = app.Execute(args); } catch (Exception ex) { AggregateException ax = ex as AggregateException; while (ax != null && ax.InnerExceptions.Count == 1) { ex = ax.InnerException; ax = ex as AggregateException; } Reporter.Error.WriteLine(ex.Message.Bold().Red()); while (ex.InnerException != null) { ex = ex.InnerException; ax = ex as AggregateException; while (ax != null && ax.InnerExceptions.Count == 1) { ex = ax.InnerException; ax = ex as AggregateException; } Reporter.Error.WriteLine(ex.Message.Bold().Red()); } Reporter.Error.WriteLine(ex.StackTrace.Bold().Red()); result = 1; } return(result); }
//////////////////////////////////// ////// EQUITY STOCK STATE ////// ////////////////////////////////// public static BrokerErrorCode EquityRefreshStockStateToday(IBroker broker, EquityStockTradeStats stockInfo) { DateTime EarliestValidMarketOpenDate = MarketUtils.GetMarketCurrentDate(); return(EquityRefreshStockState(broker, EarliestValidMarketOpenDate, EarliestValidMarketOpenDate, stockInfo)); }
public void Initialise(IBroker context, IBrokerModule thisModule) { logger = context.APILogger(); broker = context; }
public FeedService(IFeedRepository feedRepository, IBroker broker) { _feedRepository = feedRepository; _broker = broker; }
public void Initialise(IBroker context, IBrokerModule thisModule) { logger = context.APILogger(); }
public void crash(string processName) { if (processName.Contains("publisher")) { if (this.site.Equals(this.pubWithSite[processName]) || this.single) { Console.WriteLine(pubWithUrl[processName]); formP.BeginInvoke(formP.myDelegate, pubWithUrl[processName]); IPublisher publisher = (IPublisher)Activator.GetObject( typeof(IPublisher), this.pubWithUrl[processName]); SendCrashAsync RemoteDel = new SendCrashAsync(publisher.crash); IAsyncResult RemAra = RemoteDel.BeginInvoke(null, null); } else { IPuppetMaster puppetM = (IPuppetMaster)Activator.GetObject( typeof(IPuppetMaster), puppets[this.pubWithSite[processName]]); puppetM.crash(processName); } } if (processName.Contains("subscriber")) { if (this.site.Equals(this.subsWithSite[processName]) || this.single) { Console.WriteLine(subsWithUrl[processName]); formP.BeginInvoke(formP.myDelegate, subsWithUrl[processName]); ISubscriber subscriber = (ISubscriber)Activator.GetObject( typeof(ISubscriber), this.subsWithUrl[processName]); SendCrashAsync RemoteDel = new SendCrashAsync(subscriber.crash); IAsyncResult RemAra = RemoteDel.BeginInvoke(null, null); } else { IPuppetMaster puppetM = (IPuppetMaster)Activator.GetObject( typeof(IPuppetMaster), puppets[this.subsWithSite[processName]]); puppetM.crash(processName); } } if (processName.Contains("broker")) { if (this.brokers.Equals(this.brokers[processName]) || this.single) { Console.WriteLine(brokers[processName]); formP.BeginInvoke(formP.myDelegate, brokers[processName]); IBroker broker = (IBroker)Activator.GetObject( typeof(IBroker), this.brokers[processName]); SendCrashAsync RemoteDel = new SendCrashAsync(broker.crash); IAsyncResult RemAra = RemoteDel.BeginInvoke(null, null); } else { IPuppetMaster puppetM = (IPuppetMaster)Activator.GetObject( typeof(IPuppetMaster), puppets[this.brokerNameSite[processName]]); puppetM.crash(processName); } } }
public static void LogBrokerDisconnected(this ISilverbackLogger logger, IBroker broker) => BrokerDisconnected(logger.InnerLogger, broker.GetType().Name, null);
public ProduceEmptyMessageUseCaseRun(IBroker broker) { _broker = broker; }
public BackTestingTask( Func<TradingSystem> tradingSystemBuilder, IBroker broker ) { myTradingSystemBuilder = tradingSystemBuilder; Broker = broker; }
public abstract void Stop(double price, IWallet wallet, IBroker broker);
protected RobotContext(IBroker broker, User bot) { Broker = broker; Bot = bot; }
public void Init() { _broker1 = new DigiCoinBroker(0.05m, 1.49m); var broker2Commission = new List<CommissionEntry> { new CommissionEntry(40, 0.03m), new CommissionEntry(80, 0.025m), new CommissionEntry(100, 0.02m), }; _broker2 = new DigiCoinBroker(broker2Commission, 1.52m); _service = new BrokerageService(); _service.RegisterBroker(_broker1); _service.RegisterBroker(_broker2); _clientA = new Client(_service); _clientB = new Client(_service); _clientC = new Client(_service); }
public PricePublisher(IObservable <SpotPriceDto> priceStream, IBroker broker) { _priceStream = priceStream; _broker = broker; }