protected sealed override void OnTick() { ++TickNumber; Debugging.BreakOnPointOfInterest(); // Emergency stop on large draw-down BalanceMinimum = Math.Max((double)BalanceMinimum, Account.Balance * (1.0 - Settings.MaxDrawDownFrac)); if (Account.Equity < BalanceMinimum) { Debugging.Trace("Account equity (${0}) dropped below the balance minimum (${1}). Stopping".Fmt(Account.Equity, BalanceMinimum)); Print("Account equity (${0}) dropped below the balance minimum (${1}). Stopping".Fmt(Account.Equity, BalanceMinimum)); CloseAllPositions("Emergency Stop"); Stop(); return; } // Raise the Bot.Tick event before stepping the bot // Instruments are signed up to the Tick event so they will be updated first base.OnTick(); Tick.Raise(this); try { // Update the account info Broker.Update(); // Remove position sets that don't have any active positions var set_ids = Positions.Select(x => Guid_.Parse(x.Comment)).NotNull().ToHashSet(x => x.Value); foreach (var set_id in PositionSets.Keys.ToArray()) { if (set_ids.Contains(set_id)) { continue; } PositionSets.Remove(set_id); } // Step active position managers foreach (var pm in PositionManagers) { pm.Step(); } // Entry cool down if (EntryCooldown != 0 && Instrument.NewCandle) { --EntryCooldown; } // Step the bot Step(); } catch (Exception ex) { Debugging.Trace(ex.Message); Debugging.Trace(ex.StackTrace); } }
private void HandlePositionClosed(PositionClosedEventArgs args) { // Only watch positions created by this strategy var position = args.Position; if (position.Label != Label) { return; } // Close all positions in the same set var id = Guid_.Parse(position.Comment); if (id != null && PositionSets.ContainsKey(id.Value)) { var set = PositionSets[id.Value]; Broker.ClosePositions(Positions.Where(x => set.Contains(x.Id)), "Closing Set"); PositionSets.Remove(id.Value); } // Remove any position managers that are managing 'position' PositionManagers.RemoveIf(x => x.Position.Id == position.Id); try { // Notify position closed if (PositionClosed != null) { PositionClosed(this, args); } OnPositionClosed(position); } catch (Exception ex) { Debugging.Trace(ex.Message); Debugging.Trace(ex.StackTrace); } }