﻿<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/css' href='https://stocksharp.ru/css/style.css'?>
<?xml-stylesheet type='text/css' href='https://stocksharp.ru/css/bbeditor.css'?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="html">правила Security.WhenLastTradePriceMore и Security.WhenLastTradePriceLess</title>
  <id>~/topic/8922/pravila-security_whenlasttradepricemore-i-security_whenlasttradepriceless/</id>
  <rights type="text">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  <updated>2026-06-10T06:32:13Z</updated>
  <logo>https://stocksharp.ru/images/logo.png</logo>
  <link href="https://stocksharp.ru/handlers/atom.ashx?category=topic&amp;id=8922" rel="self" type="application/rss+xml" />
  <entry>
    <id>https://stocksharp.ru/posts/m/42128/</id>
    <title type="text">Добрый день. Спасибо комментарий. информация передана. </title>
    <published>2017-12-26T12:03:34Z</published>
    <updated>2017-12-26T12:03:34Z</updated>
    <author>
      <name>Support</name>
      <uri>https://stocksharp.ru/users/97869/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;p&gt;Добрый день.&lt;/p&gt;
&lt;p&gt;Спасибо комментарий. информация передана.&lt;/p&gt;
</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
  <entry>
    <id>https://stocksharp.ru/posts/m/42119/</id>
    <title type="text">Если эти правила регистрировать в методе protected override void OnStarted() на HistoryEmulationConn...</title>
    <published>2017-12-24T07:56:06Z</published>
    <updated>2017-12-24T07:56:06Z</updated>
    <author>
      <name>Иван З.</name>
      <uri>https://stocksharp.ru/users/6502/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;ol start="3"&gt;
&lt;li&gt;Если эти правила регистрировать в методе protected override void OnStarted() на HistoryEmulationConnector будет ошибка в стратегии, и стратеги работать не будет. Так как обычно на HistoryEmulationConnector сначала запускаю стратегию а после коннектор. Как то так.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;
		private void _connector_NewSecurity(Security security)
		{
			_connector.RegisterTrades(security);

			_strategy.Start();
			_connector.Start();
		}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Соответственно на момент регистрации правила коннектор запущен не будет, и в правило не сможет получить последнюю сделку, и выдаст ошибку стратегии, которую можно увидеть только в логе. Если не вести лог стратегии можно долго гадать почему она не работает.
Эта проблема справедлива для большинства подобных правил, например, у MarketRuleHelperWhenClosePriceMore та же проблема.&lt;/p&gt;
</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
  <entry>
    <id>https://stocksharp.ru/posts/m/42118/</id>
    <title type="text">вопрос 1 снимается. Оказывается надо указывать на сколько отступит цена от цены последней сделки на ...</title>
    <published>2017-12-24T07:45:24Z</published>
    <updated>2017-12-24T07:45:24Z</updated>
    <author>
      <name>Иван З.</name>
      <uri>https://stocksharp.ru/users/6502/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;p&gt;вопрос 1 снимается. Оказывается надо указывать на сколько отступит цена от цены последней сделки на момент регистрации правила, а не конкретно цену, как подумал сначала. Не очевидно конечно, но работает.&lt;/p&gt;
</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
  <entry>
    <id>https://stocksharp.ru/posts/m/41992/</id>
    <title type="text">При следующем коде WhenLastTradePriceLess вообще ни разу не сработало, WhenLastTradePriceMore срабат...</title>
    <published>2017-12-11T09:29:24Z</published>
    <updated>2017-12-11T09:29:49Z</updated>
    <author>
      <name>Иван З.</name>
      <uri>https://stocksharp.ru/users/6502/</uri>
      <email>info@stocksharp.ru</email>
    </author>
    <content type="html">&lt;ol&gt;
&lt;li&gt;При следующем коде WhenLastTradePriceLess вообще ни разу не сработало, WhenLastTradePriceMore срабатывает как то избирательно и очень редко. Хотя в connector.NewTrade я вижу, что сделки приходят. Как я понимаю они при таких условиях все сделки мне выдавать должны.
Коннектор КВИК.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class="language-C#"&gt;
//-----------------------------------------------------------------------------------------------------------------------------------
            connector.NewTrade += (t) =&amp;gt;
            {
                if (t.Security == security)
                {

                }
            };
//-----------------------------------------------------------------------------------------------------------------------------------

            security.WhenLastTradePriceLess(connector, connector, new Unit(999999999m)).Do((a) =&amp;gt;
            {

            }).Apply();

            security.WhenLastTradePriceMore(connector, connector, new Unit(0.1m)).Do((a) =&amp;gt;
            {

            }).Apply();

&lt;/code&gt;&lt;/pre&gt;
&lt;ol start="2"&gt;
&lt;li&gt;Судя по исходникам правила  Security.WhenLastTradePriceMore и Security.WhenLastTradePriceLess будут срабатывать не только при получении новой сделки но и при любом изменении инструмента, даже если новой сделки не было. Чем обосновано такое решение?&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="spoiler"&gt;
&lt;pre&gt;&lt;code class="language-C#"&gt;
		public static MarketRule&amp;lt;Security, Security&amp;gt; WhenBestAskPriceLess(this Security security, IConnector connector, Unit price)
		{
			return CreateSecurityCondition(security, connector, Level1Fields.BestAskPrice, price, true);
		}
		public static MarketRule&amp;lt;Security, Security&amp;gt; WhenLastTradePriceMore(this Security security, IConnector connector, IMarketDataProvider provider, Unit price)
		{
			return CreateLastTradeCondition(security, connector, provider, price, false);
		}
//-----------------------------------------------------------------------------------------------------------------------------------
		private static SecurityChangedRule CreateSecurityCondition(Security security, IConnector connector, Level1Fields field, Unit offset, bool isLess)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			if (offset == null)
				throw new ArgumentNullException(nameof(offset));

			if (offset.Value == 0)
				throw new ArgumentException(LocalizedStrings.Str1051, nameof(offset));

			if (offset.Value &amp;lt; 0)
				throw new ArgumentException(LocalizedStrings.Str1052, nameof(offset));

			var price = (decimal?)connector.GetSecurityValue(security, field);

			if (price == null &amp;amp;&amp;amp; offset.Type != UnitTypes.Limit)
				throw new InvalidOperationException(LocalizedStrings.Str1053);

			if (isLess)
			{
				var finishPrice = (decimal)(offset.Type == UnitTypes.Limit ? offset : price - offset);
				return new SecurityChangedRule(security, connector, s =&amp;gt;
				{
					var quote = (decimal?)connector.GetSecurityValue(s, field);
					return quote != null &amp;amp;&amp;amp; quote &amp;lt; finishPrice;
				});
			}
			else
			{
				var finishPrice = (decimal)(offset.Type == UnitTypes.Limit ? offset : price + offset);
				return new SecurityChangedRule(security, connector, s =&amp;gt;
				{
					var quote = (decimal?)connector.GetSecurityValue(s, field);
					return quote != null &amp;amp;&amp;amp; quote &amp;gt; finishPrice;
				});
			}
//-----------------------------------------------------------------------------------------------------------------------------------
		private sealed class SecurityLastTradeRule : SecurityRule&amp;lt;Security&amp;gt;
		{
			private readonly Func&amp;lt;Security, bool&amp;gt; _condition;

			public SecurityLastTradeRule(Security security, IConnector connector, Func&amp;lt;Security, bool&amp;gt; condition)
				: base(security, connector)
			{
				if (condition == null)
					throw new ArgumentNullException(nameof(condition));

				_condition = condition;

				Name = LocalizedStrings.Str1049 + &amp;quot; &amp;quot; + security;

				Connector.SecurityChanged += OnSecurityChanged;
				Connector.NewTrade += OnNewTrade;
			}

			private void OnSecurityChanged(Security security)
			{
				if (CheckLastTrade(security))
					Activate(security);
			}

			private bool CheckLastTrade(Security security)
			{
				if (Security is BasketSecurity basket)
				{
					return basket.Contains(SecurityProvider, security) &amp;amp;&amp;amp; _condition(security);
				}
				else
				{
					return security == Security &amp;amp;&amp;amp; _condition(Security);
				}
			}

			private void OnNewTrade(Trade trade)
			{
				if (CheckTrades(Security, trade))
					Activate(trade.Security);
			}

			private bool CheckTrades(Security security, Trade trade)
			{
				return security is BasketSecurity basket
					? basket.Contains(SecurityProvider, trade.Security) &amp;amp;&amp;amp; _condition(trade.Security)
					: trade.Security == security &amp;amp;&amp;amp; _condition(trade.Security);
			}

			protected override void DisposeManaged()
			{
				Connector.NewTrade -= OnNewTrade;
				Connector.SecurityChanged -= OnSecurityChanged;

				base.DisposeManaged();
			}
		}

&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;</content>
    <rights type="html">Copyright @ StockSharp Platform LLC 2010 - 2025</rights>
  </entry>
</feed>