<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Форум QUIK [тема: Разделение условий.]</title>
		<link>http://forum.quik.ru</link>
		<description>Новое в теме Разделение условий. форума  на сайте Форум QUIK [forum.quik.ru]</description>
		<language>ru</language>
		<docs>http://backend.userland.com/rss2</docs>
		<pubDate>Sun, 24 May 2026 06:45:33 +0300</pubDate>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message33070/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Спасибо, попробую все собрать все в кучу. <br />
			<i>31.08.2018 19:50:22, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message33070/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message33070/topic3898/</guid>
			<pubDate>Fri, 31 Aug 2018 19:50:22 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32978/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<br />====quote====<br /><a class="blog-p-user-name" id="bp_wFZCK222" href="/user/459/" bx-tooltip-user-id="459">Nikolay Pavlov</a> написал:<br />Опечатался... truet = true<br />=============<br />Кстати, как насчёт обновить движок форума для поддержки редактирования собственных сообщений? <br />
			<i>28.08.2018 22:03:05, Enfernuz.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32978/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32978/topic3898/</guid>
			<pubDate>Tue, 28 Aug 2018 22:03:05 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32971/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Вот <noindex><a href="https://www.lua.org/pil/4.3.1.html" target="_blank" rel="nofollow">здесь</a></noindex> описан синтаксис оператора if в Lua. <br />
			<i>28.08.2018 13:49:05, Nikolay Pavlov.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32971/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32971/topic3898/</guid>
			<pubDate>Tue, 28 Aug 2018 13:49:05 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32970/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Опечатался... truet = true <br />
			<i>28.08.2018 13:43:28, Nikolay Pavlov.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32970/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32970/topic3898/</guid>
			<pubDate>Tue, 28 Aug 2018 13:43:28 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32969/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Добрый день.<br />Да, Вы совершенно верно предположили необходимость использования дополнительного флага (в Вашем случе traling). Только нужно переменную traling заранее определить как false. Вот небольшой шаблон<br /><br />
====code====
<pre>traling = false

function main()

&nbsp;&nbsp;if traling == false then

&nbsp;&nbsp;&nbsp;&nbsp;--что-то делаем, что нужно сделать первоочередно
&nbsp;&nbsp;&nbsp;&nbsp;traling = true

&nbsp;&nbsp;end

&nbsp;&nbsp;if traling == truet then
&nbsp;&nbsp;&nbsp;&nbsp;--что-то делаем, только если выполнен первоочередный шаг
&nbsp;&nbsp;end

end
</pre>
=============
можно еще использовать вот такую конструкцию:
====code====
<pre>traling = false

function main()

&nbsp;&nbsp;if traling == false then

&nbsp;&nbsp;&nbsp;&nbsp;--что-то делаем, что нужно сделать первоочередно
&nbsp;&nbsp;&nbsp;&nbsp;traling = true

&nbsp;&nbsp;elseif traling == truet then

&nbsp;&nbsp;&nbsp;&nbsp;--в эту ветку уже не зайдем если зашли в ветку traling == false

&nbsp;&nbsp;end

end</pre>
============= <br />
			<i>28.08.2018 13:42:06, Nikolay Pavlov.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32969/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32969/topic3898/</guid>
			<pubDate>Tue, 28 Aug 2018 13:42:06 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32926/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Я выделил красным цветом где, а синим свои мысли по поводу что примерно можно сделать, не знаю на сколько верным путем иду) новичок в этом. <br />
			<i>25.08.2018 19:26:07, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32926/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32926/topic3898/</guid>
			<pubDate>Sat, 25 Aug 2018 19:26:07 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32925/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<table class="forum-spoiler"><thead onclick="if (this.nextSibling.style.display=='none') { this.nextSibling.style.display=''; BX.addClass(this, 'forum-spoiler-head-open'); } else { this.nextSibling.style.display='none'; BX.removeClass(this, 'forum-spoiler-head-open'); } BX.onCustomEvent('BX.Forum.Spoiler:toggle', [{node: this}]); event.stopPropagation();"><tr><th><div>Скрытый текст</div></th></tr></thead><tbody class="forum-spoiler" style="display:none;"><tr><td>p_classcode=&quot;SPBFUT&quot; --Код класса <br />p_seccode=&quot;SBRF&quot; --Код инструмента <br />p_account=&quot;&quot; --Код счета <br />p_clientcode=&quot;&quot; --Клиенткий код <br />p_count=2 --Размер позиции <br />p_spread=0.7 --Проскальзывание <br />p_sell_level_RSI=60 --уровень RSI, при котором продаем <br />p_buy_level_RSI=40 --уровень RSI, при котором покупаем <br />p_TRANS_ID=&quot;2&quot; --идентифкатор транзакций робота, нужен для того, что бы робот отличал свои транзакции от транзакций других роботов и ручных транзакций <br />p_TRANS_ID_STOP=&quot;3&quot; --по работе со стоп ордерами <br />p_stop_loss_level=3 --Уровень стоп лосса <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="bx-font" style="color:#ff0000"> добавить это &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p_bez_stop_level=3.1 -- Уровень безубытка</span><br />p_traling_stop_level=1 --Уровень стоп лосса, при котором мы &quot;подтягиваем&quot; стоп лосс <br />p_file = io.open(&quot;D:\\userlog.txt&quot;, &quot;w&quot;) -- тут надо указать путь к файлу лога <br />--Служебные переменные тут мы запоминаем <br />is_run = true <br />count = 0 <br />in_trade = false --признак того, что мы в позиции <br />order_num = &quot;&quot; --номер заявки по открытой сделке <br />stop_loss_num = &quot;&quot; --номер стоп заявик по открытой сделке <br />direction=&quot;&quot; --последний тип операции <br />last_price=0 --цена последней сделки по стратегии <br />in_set_stop_loss = false --признак, что мы в данный момнет ожидаем результата выставления стоп лосса <br />function main() <br /> &nbsp;while is_run do <br /> &nbsp; &nbsp;sleep(2000) <br /> &nbsp; &nbsp;robot() <br /> &nbsp;end <br />end <br />function to_log(a_msg) <br /> &nbsp;p_file:write(os.date()..&quot; &quot;..a_msg..&quot;\n&quot;) <br />end <br />function robot() <br /> &nbsp;local RSI=getNumCandles(&quot;RSI&quot;) <br /> &nbsp;local N=getNumCandles(&quot;Price&quot;) <br /> &nbsp;t,n,i=getCandlesByIndex(&quot;Price&quot;, 0, N-1, 1) <br /> &nbsp;RSI_t,RSI_n,RSI_i=getCandlesByIndex(&quot;RSI&quot;, 0, RSI-3, 2) <br /> &nbsp;--сигнла обрабатываем только если мы не в позиции <br /> &nbsp;if not(in_trade) then <br /> &nbsp; &nbsp;--сигнал на продажу (RSI пересекает уровень продажи сверху вниз) <br /> &nbsp; &nbsp;if RSI_t&#91;0&#93;.close&gt;p_sell_level_RSI and RSI_t&#91;1&#93;.close&lt;p_sell_level_RSI then <br /> &nbsp; &nbsp; &nbsp;Trade(&quot;S&quot;,count+p_count,t&#91;0&#93;.close-p_spread) <br /> &nbsp; &nbsp;end <br /> &nbsp; &nbsp;--сигнал на покупку (RSI пересекает уровень покупки снизу вверх) <br /> &nbsp; &nbsp;if RSI_t&#91;0&#93;.close&lt;p_buy_level_RSI and RSI_t&#91;1&#93;.close&gt;p_buy_level_RSI then <br /> &nbsp; &nbsp; &nbsp;Trade(&quot;B&quot;,p_count-count,t&#91;0&#93;.close+p_spread) <br /> &nbsp; &nbsp;end <br /> &nbsp;else <br /> &nbsp;<br /> &nbsp; &nbsp;--проверить состояние стопа, не надо ли его сдвигать или изменить количество <br /> &nbsp; &nbsp;stop_loss_control() <br /> &nbsp;<br /> &nbsp;end <br />end <br />--Сначала мы ищем нашу стоп заявку:для поиска используем функцию SearchItems, она у нас вызывает CALLBACK-функцию fn: <br />function fn(par1) <br /> &nbsp;if stop_loss_num==&quot;&quot; then ----номер стоп заявик по открытой сделке <br /> &nbsp; &nbsp;return false <br /> &nbsp;end <br /> &nbsp;<br /> &nbsp;if tonumber(par1) - tonumber(stop_loss_num)==0 then <br /> &nbsp; &nbsp;return true <br /> &nbsp;else <br /> &nbsp; &nbsp;return false <br /> &nbsp;end <br />end<br />function stop_loss_control() <br /> &nbsp;local N=getNumCandles(&quot;Price&quot;) -- индефикатор цены на графике N <br /> &nbsp;<br /> &nbsp;if N==nil or N==0 then return end &nbsp;<br /> &nbsp;<br /> &nbsp;p_t,p_n,p_i=getCandlesByIndex(&quot;Price&quot;, 0, N-1, 1) <br /> &nbsp;<br /> &nbsp;local NO=getNumberOf(&quot;stop_orders&quot;) -- Получение данных из таблицы Стоп-заявки: <br /> &nbsp;local is_stop_order=true <br /> &nbsp;<br /> &nbsp;if NO==nil or NO==0 then <br /> &nbsp; &nbsp;is_stop_order=false <br /> &nbsp;else <br /> &nbsp; &nbsp;t_so = SearchItems(&quot;stop_orders&quot;, 0, NO-1, fn, &quot;order_num&quot;) --order_num = &quot;&quot; --номер заявки по открытой сделке <br /> &nbsp;end <br /> &nbsp;--если стоп лосса нет, то возможно, его надо выставить <br /> &nbsp;if t_so==nil and is_stop_order then <br /> &nbsp; &nbsp;is_stop_order = false <br /> &nbsp;end <br /> &nbsp;<br /> &nbsp;if is_stop_order then <br /> &nbsp; &nbsp;if t_so&#91;1&#93;==nil then <br /> &nbsp; &nbsp; &nbsp;is_stop_order = false <br /> &nbsp; &nbsp;end <br /> &nbsp;end <br /> &nbsp;if not(is_stop_order) then <br /> &nbsp; &nbsp;if in_trade and count~=0 then --in_trade признак того, что мы в позиции <br /> &nbsp; &nbsp; &nbsp;if count&gt;0 then <br /> &nbsp; &nbsp; &nbsp; &nbsp;send_stop_loss(&quot;B&quot;,count,last_price)--формируем стоп-лосс и выставляем его, вызвав функцию send_stop_loss, last_price --цена последней сделки по стратегии <br /> &nbsp; &nbsp; &nbsp;else <br /> &nbsp; &nbsp; &nbsp; &nbsp;send_stop_loss(&quot;S&quot;,count,last_price) <br /> &nbsp; &nbsp; &nbsp;end <br /> &nbsp; &nbsp;end <br /> &nbsp; &nbsp;return <br /> &nbsp;end <br /> &nbsp;--А дальше мы вычисляем разницу в ценах, проверяем условие стоп-лосса и, при необходимости перевыставляем его. До этого кода дойдет только в том случае, если у нас уже есть выставленный стоп-лосс: <br /> &nbsp;to_log(&quot;stop_loss_control найден стоп ордер count=&quot;..count) <br /> &nbsp;t_so_item=getItem(&quot;stop_orders&quot;, t_so&#91;1&#93;) <br /> &nbsp;delta_price=0; <br /> &nbsp;<br /> &nbsp;if count&gt;0 then <br /> &nbsp; &nbsp;to_log(&quot;count&gt;0&quot;) <br /> &nbsp; &nbsp;delta_price=p_t&#91;0&#93;.close-t_so_item.condition_price; --condition это состояние, p_t строка 79 <br /> &nbsp; &nbsp;l_direction=&quot;B&quot; <br /> &nbsp;else <br /> &nbsp; &nbsp;to_log(&quot;count&lt;=0&quot;) <br /> &nbsp; &nbsp;delta_price=t_so_item.condition_price-p_t&#91;0&#93;.close <br /> &nbsp; &nbsp;l_direction=&quot;S&quot; <br /> &nbsp;end <br /> &nbsp;<br /> &nbsp;to_log(&quot;delta_price=&quot;..delta_price..&quot; t_so&#91;0&#93;.qty=&quot;..t_so_item.qty..&quot; p_t&#91;0&#93;.close=&quot;..p_t&#91;0&#93;.close) <br /> &nbsp;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="bx-font" style="color:#ff0000"> добавить тут &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if delta_price&gt;=p_bez_stop_level or count~=t_so_item.qty then </span><br /><span class="bx-font" style="color:#ff0000"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; to_log(&quot;Послылаем новую стоп заявку price=&quot;..p_t&#91;0&#93;.close..&quot; количество &quot;..count) </span><br /><span class="bx-font" style="color:#ff0000"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; send_stop_loss(l_direction,count,p_t&#91;0&#93;.close) </span><br /><span class="bx-font" style="color:#ff0000"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end </span><br /><span class="bx-font" style="color:#ff0000"> --&#91;&#91; После выставления стопа вначале должен выставиться p_bez_stop_level, а за ним p_traling_stop_level. Но до выставления безубытка трал должен игнорироваться.</span><br /> &nbsp; &nbsp; <br /><span class="bx-font" style="color:#0000ff">Размышления: &nbsp;Я думал, например изначально traling = false </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <br /> &nbsp; &nbsp; &nbsp; &nbsp;if delta_price&gt;=p_bez_stop_level or count~=t_so_item.qty then </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; to_log(&quot;Послылаем новую стоп заявку price=&quot;..p_t&#91;0&#93;.close..&quot; количество &quot;..count) </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; send_stop_loss(l_direction,count,p_t&#91;0&#93;.close) </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="bx-font" style="color:#ff0000">traling=true</span></span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if delta_price&gt;= (p_traling_stop_level or count~=t_so_item.qty) <span class="bx-font" style="color:#ff0000">and traling</span> then </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; to_log(&quot;Послылаем новую стоп заявку price=&quot;..p_t&#91;0&#93;.close..&quot; количество &quot;..count) </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; send_stop_loss(l_direction,count,p_t&#91;0&#93;.close) </span><br /><span class="bx-font" style="color:#0000ff"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end</span><br /><span class="bx-font" style="color:#0000ff"> Вроде &nbsp;пока traling = false трал не будет работать. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &#93;&#93;</span><br /> <br /> if delta_price&gt;=p_traling_stop_level or count~=t_so_item.qty then <br /> &nbsp; &nbsp;to_log(&quot;Послылаем новую стоп заявку price=&quot;..p_t&#91;0&#93;.close..&quot; количество &quot;..count) <br /> &nbsp; &nbsp;send_stop_loss(l_direction,count,p_t&#91;0&#93;.close) <br /> &nbsp;end <br />end <br />function Trade(a_oper,a_count,a_price) <br /> &nbsp;if a_count&gt;0 then --Количество сделки <br /> &nbsp; &nbsp;--Сначала пошлем обычную заявку <br /> &nbsp; &nbsp;t = { <br /> &nbsp; &nbsp;&#91;&quot;CLASSCODE&quot;&#93;=p_classcode, <br /> &nbsp; &nbsp;&#91;&quot;SECCODE&quot;&#93;=p_seccode, <br /> &nbsp; &nbsp;&#91;&quot;ACTION&quot;&#93;=&quot;NEW_ORDER&quot;, <br /> &nbsp; &nbsp;&#91;&quot;ACCOUNT&quot;&#93;=p_account, <br /> &nbsp; &nbsp;&#91;&quot;CLIENT_CODE&quot;&#93;=p_clientcode, <br /> &nbsp; &nbsp;&#91;&quot;TYPE&quot;&#93;=&quot;L&quot;, <br /> &nbsp; &nbsp;&#91;&quot;OPERATION&quot;&#93;=a_oper, <br /> &nbsp; &nbsp;&#91;&quot;QUANTITY&quot;&#93;=tostring(a_count), <br /> &nbsp; &nbsp;&#91;&quot;PRICE&quot;&#93;=tostring(a_price), <br /> &nbsp; &nbsp;&#91;&quot;EXPIRY_DATE&quot;&#93;=&quot;GTC&quot;, <br /> &nbsp; &nbsp;&#91;&quot;TRANS_ID&quot;&#93;=p_TRANS_ID <br /> &nbsp; &nbsp;} <br /> &nbsp; &nbsp;res=sendTransaction(t) <br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;--заявку послали и сразу же мы оказались в позиции и будем в ней до тех пор, пока не закроется сделка <br /> &nbsp; &nbsp;--или пока не будет доказано обратное (мы узнаем, что сделка не прошла) <br /> &nbsp; &nbsp;in_trade=true <br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;direction=a_oper--последний тип операции <br /> &nbsp; &nbsp;message(&quot;Количество сделки &quot;..tostring(a_count)..&quot; тип операции &quot;..a_oper..&quot; Цена &quot;..a_price,1) <br /> &nbsp;end <br />end<br />--Обработчик события сделки. <br />function OnTrade(trade) <br /> &nbsp;nord=trade&#91;&quot;order_num&quot;&#93; <br /> &nbsp;price=trade&#91;&quot;price&quot;&#93; <br /> &nbsp;to_log(&quot;Совершена сделка: номер заявки &quot;..tostring(nord)..&quot;; цена &quot;..tostring(price)..&quot;: количество &quot;..tostring(trade&#91;&quot;qty&quot;&#93;)) <br /> &nbsp;if nord==order_num then <br /> &nbsp; &nbsp;qty=trade&#91;&quot;qty&quot;&#93; <br /> &nbsp; &nbsp;if direction==&quot;B&quot; then <br /> &nbsp; &nbsp; &nbsp;count=count+qty <br /> &nbsp; &nbsp;else <br /> &nbsp; &nbsp; &nbsp;count=count-qty <br /> &nbsp; &nbsp;end <br /> &nbsp; &nbsp;send_stop_loss(direction,count,price) <br /> &nbsp; &nbsp;last_price=price <br /> &nbsp;end <br />end <br />--Обработчик события создания стоп заявки <br />function OnStopOrder(stop_order) <br /> &nbsp;--бит 0 (0x1) Заявка активна, иначе не активна <br /> &nbsp;if stop_order&#91;&quot;order_num&quot;&#93;==stop_loss_num and bit.band(stop_order&#91;&quot;flags&quot;&#93;,0x1)==0x1 then <br /> &nbsp; &nbsp;to_log(&quot;сняли признак что мы в процессе выставления стоп оредра&quot;) <br /> &nbsp; &nbsp;in_set_stop_loss=false <br /> &nbsp;end <br /> &nbsp;--бит 0 (0x1) Заявка активна, иначе не активна, <br /> &nbsp;--бит 1 (0x2) Заявка снята. Если не установлен и значение бита 0 равно 0, то заявка исполнена <br /> &nbsp;--в этом случае мы считаем, что позция закрыта по стоп лоссу <br /> &nbsp;if stop_order&#91;&quot;order_num&quot;&#93;==stop_loss_num and bit.band(stop_order&#91;&quot;flags&quot;&#93;,0x1)==0x0 and bit.band(stop_order&#91;&quot;flags&quot;&#93;,0x2)==0x0 then --stop_loss_num = &quot;&quot; --номер стоп заявик по открытой сделке <br /> &nbsp; &nbsp;in_set_stop_loss=false <br /> &nbsp; &nbsp;count=0 <br /> &nbsp;end <br />end <br />--Удалить стоп лосс <br />function delete_stop_loss(a_num) <br /> &nbsp;t = { <br /> &nbsp;&#91;&quot;CLASSCODE&quot;&#93;=p_classcode, <br /> &nbsp;&#91;&quot;SECCODE&quot;&#93;=p_seccode, <br /> &nbsp;&#91;&quot;ACTION&quot;&#93;=&quot;KILL_STOP_ORDER&quot;, <br /> &nbsp;&#91;&quot;ACCOUNT&quot;&#93;=p_account, <br /> &nbsp;&#91;&quot;CLIENT_CODE&quot;&#93;=p_clientcode, <br /> &nbsp;&#91;&quot;TYPE&quot;&#93;=&quot;L&quot;, <br /> &nbsp;&#91;&quot;OPERATION&quot;&#93;=l_oper, <br /> &nbsp;&#91;&quot;STOP_ORDER_KIND&quot;&#93;=&quot;SIMPLE_STOP_ORDER&quot;, <br /> &nbsp;&#91;&quot;TRANS_ID&quot;&#93;=p_TRANS_ID_STOP, <br /> &nbsp;&#91;&quot;STOP_ORDER_KEY&quot;&#93;=tostring(a_num) <br /> &nbsp;} <br /> &nbsp;res=sendTransaction(t) <br /> &nbsp;message(&quot;Удаляем стоп лосс: сообщение &quot;..res..&quot;; номер &quot;..a_num,1) <br />end<br />--Послать стоп заявку <br />function send_stop_loss(a_direction,a_count,a_price) <br /> &nbsp;to_log(&quot;send_stop_loss in_set_stop_loss=&quot;..tostring(in_set_stop_loss)) <br /> &nbsp;if not(in_set_stop_loss) then <br /> &nbsp; &nbsp;if stop_loss_num~=&quot;&quot; then <br /> &nbsp; &nbsp; &nbsp;delete_stop_loss(stop_loss_num) <br /> &nbsp; &nbsp;end <br /> &nbsp; &nbsp;if a_direction==&quot;B&quot; then <br /> &nbsp; &nbsp; &nbsp;l_oper=&quot;S&quot; <br /> &nbsp; &nbsp; &nbsp;l_count=a_count <br /> &nbsp; &nbsp; &nbsp;dir=-1 <br /> &nbsp; &nbsp;else <br /> &nbsp; &nbsp; &nbsp;l_oper=&quot;B&quot; <br /> &nbsp; &nbsp; &nbsp;l_count=-a_count <br /> &nbsp; &nbsp; &nbsp;dir=1 <br /> &nbsp; &nbsp;end <br /> &nbsp; &nbsp;l_price=a_price+p_stop_loss_level*dir <br /> &nbsp; &nbsp;if l_count&gt;0 then <br /> &nbsp; &nbsp; &nbsp;to_log(&quot;send_stop_loss Зашли сюда&quot;,1) <br /> &nbsp; &nbsp; &nbsp;in_set_stop_loss=true <br /> &nbsp; &nbsp; &nbsp;<br /> &nbsp; &nbsp; &nbsp;--Пошлем стоп заявку <br /> &nbsp; &nbsp; &nbsp;t = { <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;CLASSCODE&quot;&#93;=p_classcode, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;SECCODE&quot;&#93;=p_seccode, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;ACTION&quot;&#93;=&quot;NEW_STOP_ORDER&quot;, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;ACCOUNT&quot;&#93;=p_account, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;CLIENT_CODE&quot;&#93;=p_clientcode, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;TYPE&quot;&#93;=&quot;L&quot;, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;OPERATION&quot;&#93;=l_oper, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;QUANTITY&quot;&#93;=tostring(l_count), <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;PRICE&quot;&#93;=tostring(l_price+p_spread*dir), <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;EXPIRY_DATE&quot;&#93;=&quot;GTC&quot;, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;STOPPRICE&quot;&#93;=tostring(l_price), <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;STOP_ORDER_KIND&quot;&#93;=&quot;SIMPLE_STOP_ORDER&quot;, <br /> &nbsp; &nbsp; &nbsp;&#91;&quot;TRANS_ID&quot;&#93;=p_TRANS_ID_STOP <br /> &nbsp; &nbsp; &nbsp;} <br /> &nbsp; &nbsp; &nbsp;res=sendTransaction(t) <br /> &nbsp; &nbsp; &nbsp;message(res,1) <br /> &nbsp; &nbsp; &nbsp;to_log(&quot;Выставли стоп заявку &quot;..l_oper) <br /> &nbsp; &nbsp;end <br /> &nbsp;end <br />end<br />--обработка события транзакции <br />function OnTransReply(trans_reply) <br /> &nbsp;id=tostring(trans_reply&#91;&quot;trans_id&quot;&#93;) <br /> &nbsp;<br /> &nbsp;to_log(&quot;Обработка транзакции &quot;..id) <br /> &nbsp;<br /> &nbsp;--если это наша транзакция, обработаем ее <br /> &nbsp;if id==p_TRANS_ID then <br /> &nbsp; &nbsp;nord=trans_reply&#91;&quot;order_num&quot;&#93; <br /> &nbsp;<br /> &nbsp; &nbsp;to_log(&quot;Обработка транзакции номер заявки &quot;..nord) <br /> &nbsp;<br /> &nbsp; &nbsp;--если заявка выставилась - запоминаем ее номер, иначе считаем, что мы не в сделке <br /> &nbsp; &nbsp;if nord==nil or nord==0 or nord==&quot;0&quot; then <br /> &nbsp; &nbsp; &nbsp;message(&quot;Заявка не выставилась &quot;,1) <br /> &nbsp; &nbsp; &nbsp;in_trade=false <br /> &nbsp; &nbsp;else <br /> &nbsp; &nbsp; &nbsp;order_num=nord <br /> &nbsp; &nbsp;end <br /> &nbsp;end<br /> &nbsp;if id==p_TRANS_ID_STOP then <br /> &nbsp; &nbsp;message(&quot;Сообщение транзакции стоп ордера &quot;..trans_reply&#91;&quot;result_msg&quot;&#93;,1) <br /> &nbsp; &nbsp;nord=trans_reply&#91;&quot;order_num&quot;&#93; --Номер заявки <br /> &nbsp; &nbsp;--если заявка выставилась - запоминаем ее номер, иначе считаем, что мы закончили выставлять стоп заявку <br /> &nbsp; &nbsp;if nord==nil then <br /> &nbsp; &nbsp; &nbsp;message(&quot;Стоп заявка не выставилась &quot;,1) <br /> &nbsp; &nbsp; &nbsp;in_set_stop_loss=false <br /> &nbsp; &nbsp; &nbsp;stop_loss_num=&quot;&quot; <br /> &nbsp; &nbsp;else <br /> &nbsp; &nbsp; &nbsp;stop_loss_num=nord <br /> &nbsp; &nbsp;end <br /> &nbsp;end <br />end <br />function OnStop(stop_flag) <br /> &nbsp; &nbsp;is_run=false <br /> &nbsp; &nbsp;stop_flag=1 <br /> &nbsp; &nbsp;p_file:close(); <br />end </td></tr></tbody></table> <br />
			<i>25.08.2018 19:23:42, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32925/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32925/topic3898/</guid>
			<pubDate>Sat, 25 Aug 2018 19:23:42 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32824/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Добрый день.<br />Обработал Ваш код, иначе читать такой объем в таком виде невозможно. Укажите, пожалуйста, в каком именно месте/функции Вам нужно разделить условия, описанные выше<table class="forum-spoiler"><thead onclick="if (this.nextSibling.style.display=='none') { this.nextSibling.style.display=''; BX.addClass(this, 'forum-spoiler-head-open'); } else { this.nextSibling.style.display='none'; BX.removeClass(this, 'forum-spoiler-head-open'); } BX.onCustomEvent('BX.Forum.Spoiler:toggle', [{node: this}]); event.stopPropagation();"><tr><th><div>Скрытый текст</div></th></tr></thead><tbody class="forum-spoiler" style="display:none;"><tr><td><br />
====code====
<pre>p_classcode="SPBFUT" --Код класса 
p_seccode="SBRF" --Код инструмента 
p_account="" --Код счета 
p_clientcode="" --Клиенткий код 
p_count=2 --Размер позиции 
p_spread=0.7 --Проскальзывание 
p_sell_level_RSI=60 --уровень RSI, при котором продаем 
p_buy_level_RSI=40 --уровень RSI, при котором покупаем 
p_TRANS_ID="2" --идентифкатор транзакций робота, нужен для того, что бы робот отличал свои транзакции от транзакций других роботов и ручных транзакций 
p_TRANS_ID_STOP="3" --по работе со стоп ордерами 
p_stop_loss_level=3 --Уровень стоп лосса 
p_traling_stop_level=3.1 --Уровень стоп лосса, при котором мы "подтягиваем" стоп лосс 
p_file = io.open("D:&#92;&#92;userlog.txt", "w") -- тут надо указать путь к файлу лога 

--Служебные переменные тут мы запоминаем 
is_run = true 
count = 0 
in_trade = false --признак того, что мы в позиции 
order_num = "" --номер заявки по открытой сделке 
stop_loss_num = "" --номер стоп заявик по открытой сделке 
direction="" --последний тип операции 
last_price=0 --цена последней сделки по стратегии 
in_set_stop_loss = false --признак, что мы в данный момнет ожидаем результата выставления стоп лосса 

function main() 
&nbsp;&nbsp;while is_run do 
&nbsp;&nbsp;&nbsp;&nbsp;sleep(2000) 
&nbsp;&nbsp;&nbsp;&nbsp;robot() 
&nbsp;&nbsp;end 
end 

function to_log(a_msg) 
&nbsp;&nbsp;p_file:write(os.date().." "..a_msg.."&#92;n") 
end 

function robot() 
&nbsp;&nbsp;local RSI=getNumCandles("RSI") 
&nbsp;&nbsp;local N=getNumCandles("Price") 
&nbsp;&nbsp;t,n,i=getCandlesByIndex("Price", 0, N-1, 1) 
&nbsp;&nbsp;RSI_t,RSI_n,RSI_i=getCandlesByIndex("RSI", 0, RSI-3, 2) 

&nbsp;&nbsp;--сигнла обрабатываем только если мы не в позиции 
&nbsp;&nbsp;if not(in_trade) then 

&nbsp;&nbsp;&nbsp;&nbsp;--сигнал на продажу (RSI пересекает уровень продажи сверху вниз) 
&nbsp;&nbsp;&nbsp;&nbsp;if RSI_t&#91;0&#93;.close&#62;p_sell_level_RSI and RSI_t&#91;1&#93;.close&#60;p_sell_level_RSI then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Trade("S",count+p_count,t&#91;0&#93;.close-p_spread) 
&nbsp;&nbsp;&nbsp;&nbsp;end 

&nbsp;&nbsp;&nbsp;&nbsp;--сигнал на покупку (RSI пересекает уровень покупки снизу вверх) 
&nbsp;&nbsp;&nbsp;&nbsp;if RSI_t&#91;0&#93;.close&#60;p_buy_level_RSI and RSI_t&#91;1&#93;.close&#62;p_buy_level_RSI then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Trade("B",p_count-count,t&#91;0&#93;.close+p_spread) 
&nbsp;&nbsp;&nbsp;&nbsp;end 

&nbsp;&nbsp;else 
&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;--проверить состояние стопа, не надо ли его сдвигать или изменить количество 
&nbsp;&nbsp;&nbsp;&nbsp;stop_loss_control() 
&nbsp;&nbsp;
&nbsp;&nbsp;end 

end 

--Сначала мы ищем нашу стоп заявку:для поиска используем функцию SearchItems, она у нас вызывает CALLBACK-функцию fn: 
function fn(par1) 
&nbsp;&nbsp;if stop_loss_num=="" then ----номер стоп заявик по открытой сделке 
&nbsp;&nbsp;&nbsp;&nbsp;return false 
&nbsp;&nbsp;end 
&nbsp;&nbsp;
&nbsp;&nbsp;if tonumber(par1) - tonumber(stop_loss_num)==0 then 
&nbsp;&nbsp;&nbsp;&nbsp;return true 
&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;return false 
&nbsp;&nbsp;end 
end

function stop_loss_control() 
&nbsp;&nbsp;local N=getNumCandles("Price") -- индефикатор цены на графике N 
&nbsp;&nbsp;
&nbsp;&nbsp;if N==nil or N==0 then return end&nbsp;&nbsp;
&nbsp;&nbsp;
&nbsp;&nbsp;p_t,p_n,p_i=getCandlesByIndex("Price", 0, N-1, 1) 
&nbsp;&nbsp;
&nbsp;&nbsp;local NO=getNumberOf("stop_orders") -- Получение данных из таблицы Стоп-заявки: 
&nbsp;&nbsp;local is_stop_order=true 
&nbsp;&nbsp;
&nbsp;&nbsp;if NO==nil or NO==0 then 
&nbsp;&nbsp;&nbsp;&nbsp;is_stop_order=false 
&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;t_so = SearchItems("stop_orders", 0, NO-1, fn, "order_num") --order_num = "" --номер заявки по открытой сделке 
&nbsp;&nbsp;end 

&nbsp;&nbsp;--если стоп лосса нет, то возможно, его надо выставить 
&nbsp;&nbsp;if t_so==nil and is_stop_order then 
&nbsp;&nbsp;&nbsp;&nbsp;is_stop_order = false 
&nbsp;&nbsp;end 
&nbsp;&nbsp;
&nbsp;&nbsp;if is_stop_order then 
&nbsp;&nbsp;&nbsp;&nbsp;if t_so&#91;1&#93;==nil then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;is_stop_order = false 
&nbsp;&nbsp;&nbsp;&nbsp;end 
&nbsp;&nbsp;end 

&nbsp;&nbsp;if not(is_stop_order) then 
&nbsp;&nbsp;&nbsp;&nbsp;if in_trade and count~=0 then --in_trade признак того, что мы в позиции 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if count&#62;0 then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send_stop_loss("B",count,last_price)--формируем стоп-лосс и выставляем его, вызвав функцию send_stop_loss, last_price --цена последней сделки по стратегии 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send_stop_loss("S",count,last_price) 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end 
&nbsp;&nbsp;&nbsp;&nbsp;end 
&nbsp;&nbsp;&nbsp;&nbsp;return 
&nbsp;&nbsp;end 

&nbsp;&nbsp;--А дальше мы вычисляем разницу в ценах, проверяем условие стоп-лосса и, при необходимости перевыставляем его. До этого кода дойдет только в том случае, если у нас уже есть выставленный стоп-лосс: 
&nbsp;&nbsp;to_log("stop_loss_control найден стоп ордер count="..count) 
&nbsp;&nbsp;t_so_item=getItem("stop_orders", t_so&#91;1&#93;) 
&nbsp;&nbsp;delta_price=0; 
&nbsp;&nbsp;
&nbsp;&nbsp;if count&#62;0 then 
&nbsp;&nbsp;&nbsp;&nbsp;to_log("count&#62;0") 
&nbsp;&nbsp;&nbsp;&nbsp;delta_price=p_t&#91;0&#93;.close-t_so_item.condition_price; --condition это состояние, p_t строка 79 
&nbsp;&nbsp;&nbsp;&nbsp;l_direction="B" 
&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;to_log("count&#60;=0") 
&nbsp;&nbsp;&nbsp;&nbsp;delta_price=t_so_item.condition_price-p_t&#91;0&#93;.close 
&nbsp;&nbsp;&nbsp;&nbsp;l_direction="S" 
&nbsp;&nbsp;end 
&nbsp;&nbsp;
&nbsp;&nbsp;to_log("delta_price="..delta_price.." t_so&#91;0&#93;.qty="..t_so_item.qty.." p_t&#91;0&#93;.close="..p_t&#91;0&#93;.close) 
&nbsp;&nbsp;
&nbsp;&nbsp;if delta_price&#62;=p_traling_stop_level or count~=t_so_item.qty then 
&nbsp;&nbsp;&nbsp;&nbsp;to_log("Послылаем новую стоп заявку price="..p_t&#91;0&#93;.close.." количество "..count) 
&nbsp;&nbsp;&nbsp;&nbsp;send_stop_loss(l_direction,count,p_t&#91;0&#93;.close) 
&nbsp;&nbsp;end 

end 

function Trade(a_oper,a_count,a_price) 
&nbsp;&nbsp;if a_count&#62;0 then --Количество сделки 
&nbsp;&nbsp;&nbsp;&nbsp;--Сначала пошлем обычную заявку 
&nbsp;&nbsp;&nbsp;&nbsp;t = { 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"CLASSCODE"&#93;=p_classcode, 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"SECCODE"&#93;=p_seccode, 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"ACTION"&#93;="NEW_ORDER", 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"ACCOUNT"&#93;=p_account, 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"CLIENT_CODE"&#93;=p_clientcode, 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"TYPE"&#93;="L", 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"OPERATION"&#93;=a_oper, 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"QUANTITY"&#93;=tostring(a_count), 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"PRICE"&#93;=tostring(a_price), 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"EXPIRY_DATE"&#93;="GTC", 
&nbsp;&nbsp;&nbsp;&nbsp;&#91;"TRANS_ID"&#93;=p_TRANS_ID 
&nbsp;&nbsp;&nbsp;&nbsp;} 
&nbsp;&nbsp;&nbsp;&nbsp;res=sendTransaction(t) 
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;--заявку послали и сразу же мы оказались в позиции и будем в ней до тех пор, пока не закроется сделка 
&nbsp;&nbsp;&nbsp;&nbsp;--или пока не будет доказано обратное (мы узнаем, что сделка не прошла) 
&nbsp;&nbsp;&nbsp;&nbsp;in_trade=true 
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;direction=a_oper--последний тип операции 
&nbsp;&nbsp;&nbsp;&nbsp;message("Количество сделки "..tostring(a_count).." тип операции "..a_oper.." Цена "..a_price,1) 
&nbsp;&nbsp;end 
end

--Обработчик события сделки. 
function OnTrade(trade) 
&nbsp;&nbsp;nord=trade&#91;"order_num"&#93; 
&nbsp;&nbsp;price=trade&#91;"price"&#93; 
&nbsp;&nbsp;to_log("Совершена сделка: номер заявки "..tostring(nord).."; цена "..tostring(price)..": количество "..tostring(trade&#91;"qty"&#93;)) 
&nbsp;&nbsp;if nord==order_num then 
&nbsp;&nbsp;&nbsp;&nbsp;qty=trade&#91;"qty"&#93; 

&nbsp;&nbsp;&nbsp;&nbsp;if direction=="B" then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count=count+qty 
&nbsp;&nbsp;&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count=count-qty 
&nbsp;&nbsp;&nbsp;&nbsp;end 

&nbsp;&nbsp;&nbsp;&nbsp;send_stop_loss(direction,count,price) 
&nbsp;&nbsp;&nbsp;&nbsp;last_price=price 
&nbsp;&nbsp;end 
end 

--Обработчик события создания стоп заявки 
function OnStopOrder(stop_order) 
&nbsp;&nbsp;--бит 0 (0x1) Заявка активна, иначе не активна 
&nbsp;&nbsp;if stop_order&#91;"order_num"&#93;==stop_loss_num and bit.band(stop_order&#91;"flags"&#93;,0x1)==0x1 then 
&nbsp;&nbsp;&nbsp;&nbsp;to_log("сняли признак что мы в процессе выставления стоп оредра") 
&nbsp;&nbsp;&nbsp;&nbsp;in_set_stop_loss=false 
&nbsp;&nbsp;end 

&nbsp;&nbsp;--бит 0 (0x1) Заявка активна, иначе не активна, 
&nbsp;&nbsp;--бит 1 (0x2) Заявка снята. Если не установлен и значение бита 0 равно 0, то заявка исполнена 
&nbsp;&nbsp;--в этом случае мы считаем, что позция закрыта по стоп лоссу 
&nbsp;&nbsp;if stop_order&#91;"order_num"&#93;==stop_loss_num and bit.band(stop_order&#91;"flags"&#93;,0x1)==0x0 and bit.band(stop_order&#91;"flags"&#93;,0x2)==0x0 then --stop_loss_num = "" --номер стоп заявик по открытой сделке 
&nbsp;&nbsp;&nbsp;&nbsp;in_set_stop_loss=false 
&nbsp;&nbsp;&nbsp;&nbsp;count=0 
&nbsp;&nbsp;end 
end 

--Удалить стоп лосс 
function delete_stop_loss(a_num) 
&nbsp;&nbsp;t = { 
&nbsp;&nbsp;&#91;"CLASSCODE"&#93;=p_classcode, 
&nbsp;&nbsp;&#91;"SECCODE"&#93;=p_seccode, 
&nbsp;&nbsp;&#91;"ACTION"&#93;="KILL_STOP_ORDER", 
&nbsp;&nbsp;&#91;"ACCOUNT"&#93;=p_account, 
&nbsp;&nbsp;&#91;"CLIENT_CODE"&#93;=p_clientcode, 
&nbsp;&nbsp;&#91;"TYPE"&#93;="L", 
&nbsp;&nbsp;&#91;"OPERATION"&#93;=l_oper, 
&nbsp;&nbsp;&#91;"STOP_ORDER_KIND"&#93;="SIMPLE_STOP_ORDER", 
&nbsp;&nbsp;&#91;"TRANS_ID"&#93;=p_TRANS_ID_STOP, 
&nbsp;&nbsp;&#91;"STOP_ORDER_KEY"&#93;=tostring(a_num) 
&nbsp;&nbsp;} 
&nbsp;&nbsp;res=sendTransaction(t) 
&nbsp;&nbsp;message("Удаляем стоп лосс: сообщение "..res.."; номер "..a_num,1) 
end

--Послать стоп заявку 
function send_stop_loss(a_direction,a_count,a_price) 
&nbsp;&nbsp;to_log("send_stop_loss in_set_stop_loss="..tostring(in_set_stop_loss)) 
&nbsp;&nbsp;if not(in_set_stop_loss) then 
&nbsp;&nbsp;&nbsp;&nbsp;if stop_loss_num~="" then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;delete_stop_loss(stop_loss_num) 
&nbsp;&nbsp;&nbsp;&nbsp;end 

&nbsp;&nbsp;&nbsp;&nbsp;if a_direction=="B" then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;l_oper="S" 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;l_count=a_count 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dir=-1 
&nbsp;&nbsp;&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;l_oper="B" 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;l_count=-a_count 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dir=1 
&nbsp;&nbsp;&nbsp;&nbsp;end 

&nbsp;&nbsp;&nbsp;&nbsp;l_price=a_price+p_stop_loss_level*dir 
&nbsp;&nbsp;&nbsp;&nbsp;if l_count&#62;0 then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;to_log("send_stop_loss Зашли сюда",1) 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;in_set_stop_loss=true 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;--Пошлем стоп заявку 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t = { 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"CLASSCODE"&#93;=p_classcode, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"SECCODE"&#93;=p_seccode, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"ACTION"&#93;="NEW_STOP_ORDER", 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"ACCOUNT"&#93;=p_account, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"CLIENT_CODE"&#93;=p_clientcode, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"TYPE"&#93;="L", 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"OPERATION"&#93;=l_oper, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"QUANTITY"&#93;=tostring(l_count), 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"PRICE"&#93;=tostring(l_price+p_spread*dir), 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"EXPIRY_DATE"&#93;="GTC", 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"STOPPRICE"&#93;=tostring(l_price), 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"STOP_ORDER_KIND"&#93;="SIMPLE_STOP_ORDER", 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#91;"TRANS_ID"&#93;=p_TRANS_ID_STOP 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;res=sendTransaction(t) 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;message(res,1) 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;to_log("Выставли стоп заявку "..l_oper) 
&nbsp;&nbsp;&nbsp;&nbsp;end 
&nbsp;&nbsp;end 
end

--обработка события транзакции 
function OnTransReply(trans_reply) 
&nbsp;&nbsp;id=tostring(trans_reply&#91;"trans_id"&#93;) 
&nbsp;&nbsp;
&nbsp;&nbsp;to_log("Обработка транзакции "..id) 
&nbsp;&nbsp;
&nbsp;&nbsp;--если это наша транзакция, обработаем ее 
&nbsp;&nbsp;if id==p_TRANS_ID then 
&nbsp;&nbsp;&nbsp;&nbsp;nord=trans_reply&#91;"order_num"&#93; 
&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;to_log("Обработка транзакции номер заявки "..nord) 
&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;--если заявка выставилась - запоминаем ее номер, иначе считаем, что мы не в сделке 
&nbsp;&nbsp;&nbsp;&nbsp;if nord==nil or nord==0 or nord=="0" then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;message("Заявка не выставилась ",1) 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;in_trade=false 
&nbsp;&nbsp;&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;order_num=nord 
&nbsp;&nbsp;&nbsp;&nbsp;end 
&nbsp;&nbsp;end

&nbsp;&nbsp;if id==p_TRANS_ID_STOP then 
&nbsp;&nbsp;&nbsp;&nbsp;message("Сообщение транзакции стоп ордера "..trans_reply&#91;"result_msg"&#93;,1) 
&nbsp;&nbsp;&nbsp;&nbsp;nord=trans_reply&#91;"order_num"&#93; --Номер заявки 

&nbsp;&nbsp;&nbsp;&nbsp;--если заявка выставилась - запоминаем ее номер, иначе считаем, что мы закончили выставлять стоп заявку 
&nbsp;&nbsp;&nbsp;&nbsp;if nord==nil then 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;message("Стоп заявка не выставилась ",1) 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;in_set_stop_loss=false 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stop_loss_num="" 
&nbsp;&nbsp;&nbsp;&nbsp;else 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stop_loss_num=nord 
&nbsp;&nbsp;&nbsp;&nbsp;end 
&nbsp;&nbsp;end 
end 

function OnStop(stop_flag) 
&nbsp;&nbsp;&nbsp;&nbsp;is_run=false 
&nbsp;&nbsp;&nbsp;&nbsp;stop_flag=1 
&nbsp;&nbsp;&nbsp;&nbsp;p_file:close(); 
end
</pre>
=============
</td></tr></tbody></table> <br />
			<i>22.08.2018 06:42:29, Nikolay Pavlov.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32824/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32824/topic3898/</guid>
			<pubDate>Wed, 22 Aug 2018 06:42:29 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32800/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<table class="forum-spoiler"><thead onclick="if (this.nextSibling.style.display=='none') { this.nextSibling.style.display=''; BX.addClass(this, 'forum-spoiler-head-open'); } else { this.nextSibling.style.display='none'; BX.removeClass(this, 'forum-spoiler-head-open'); } BX.onCustomEvent('BX.Forum.Spoiler:toggle', [{node: this}]); event.stopPropagation();"><tr><th><div>Скрытый текст</div></th></tr></thead><tbody class="forum-spoiler" style="display:none;"><tr><td>--Параметры:<br />p_classcode=&quot;SPBFUT&quot; --Код класса<br />p_seccode=&quot;SBRF&quot; --Код инструмента<br />p_account=&quot;&quot; --Код счета<br />p_clientcode=&quot;&quot; --Клиенткий код<br />p_count=2 --Размер позиции<br />p_spread=0.7 --Проскальзывание<br />p_sell_level_RSI=60 --уровень RSI, при котором продаем<br />p_buy_level_RSI=40 --уровень RSI, при котором покупаем<br />p_TRANS_ID=&quot;2&quot; --идентифкатор транзакций робота, нужен для того, что бы робот отличал свои транзакции от транзакций других роботов и ручных транзакций<br />p_TRANS_ID_STOP=&quot;3&quot; --по работе со стоп ордерами<br />p_stop_loss_level=3 --Уровень стоп лосса<br />p_traling_stop_level=3.1 --Уровень стоп лосса, при котором мы &quot;подтягиваем&quot; стоп лосс<br />p_file = io.open(&quot;D:\\userlog.txt&quot;, &quot;w&quot;) -- тут надо указать путь к файлу лога<br />--Служебные переменные тут мы запоминаем<br />is_run = true<br />count = 0 <br />in_trade = false --признак того, что мы в позиции<br />order_num = &quot;&quot; --номер заявки по открытой сделке<br />stop_loss_num = &quot;&quot; --номер стоп заявик по открытой сделке<br />direction=&quot;&quot; &nbsp;--последний тип операции<br />last_price=0 --цена последней сделки по стратегии<br />in_set_stop_loss = false --признак, что мы в данный момнет ожидаем результата выставления стоп лосса<br /><br />function main()<br /> while is_run do<br /> &nbsp;sleep(2000)<br /> &nbsp;robot()<br /> end<br />end<br />function to_log(a_msg)<br /> p_file:write(os.date()..&quot; &nbsp; &quot;..a_msg..&quot;\n&quot;) <br />end<br />function robot()<br /> local RSI=getNumCandles(&quot;RSI&quot;)<br /> local N=getNumCandles(&quot;Price&quot;)<br /> t,n,i=getCandlesByIndex(&quot;Price&quot;, 0, N-1, 1) <br /> RSI_t,RSI_n,RSI_i=getCandlesByIndex(&quot;RSI&quot;, 0, RSI-3, 2) <br /> <br /> --сигнла обрабатываем только если мы не в позиции<br /> if not(in_trade) then<br /> &nbsp;--сигнал на продажу (RSI пересекает уровень продажи сверху вниз)<br /> &nbsp;if RSI_t&#91;0&#93;.close&gt;p_sell_level_RSI and RSI_t&#91;1&#93;.close&lt;p_sell_level_RSI then<br /> &nbsp; Trade(&quot;S&quot;,count+p_count,t&#91;0&#93;.close-p_spread)<br /> &nbsp;end<br /> &nbsp;<br /> &nbsp;--сигнал на покупку (RSI пересекает уровень покупки снизу вверх)<br /> &nbsp;if RSI_t&#91;0&#93;.close&lt;p_buy_level_RSI and RSI_t&#91;1&#93;.close&gt;p_buy_level_RSI then<br /> &nbsp; Trade(&quot;B&quot;,p_count-count,t&#91;0&#93;.close+p_spread)<br /> &nbsp;end<br /> &nbsp;<br /> else <br /> &nbsp;--проверить состояние стопа, не надо ли его сдвигать или изменить количество<br /> &nbsp;stop_loss_control()<br /> end<br /> &nbsp;<br />end<br />--Сначала мы ищем нашу стоп заявку:для поиска используем функцию SearchItems, она у нас вызывает CALLBACK-функцию fn:<br />function fn(par1)<br /> if stop_loss_num==&quot;&quot; then ----номер стоп заявик по открытой сделке<br /> &nbsp;return false<br /> end<br /> if tonumber(par1) - tonumber(stop_loss_num)==0 then<br /> &nbsp;return true<br /> else<br /> &nbsp;return false<br /> end<br />end<br />function stop_loss_control()<br /> local N=getNumCandles(&quot;Price&quot;) -- индефикатор цены на графике N<br /> if N==nil or N==0 then return end<br /> p_t,p_n,p_i=getCandlesByIndex(&quot;Price&quot;, 0, N-1, 1) <br /> <br /> local NO=getNumberOf(&quot;stop_orders&quot;) -- Получение данных из таблицы Стоп-заявки:<br /> local is_stop_order=true<br /> if NO==nil or NO==0 then <br /> &nbsp;is_stop_order=false <br /> else<br /> &nbsp;t_so = &nbsp;SearchItems(&quot;stop_orders&quot;, 0, NO-1, fn, &quot;order_num&quot;) --order_num = &quot;&quot; --номер заявки по открытой сделке<br /> end<br /> <br /> --если стоп лосса нет, то возможно, его надо выставить<br /> if t_so==nil and is_stop_order then<br /> &nbsp;is_stop_order = false<br /> end<br /> if is_stop_order then<br /> &nbsp;if t_so&#91;1&#93;==nil then<br /> &nbsp; is_stop_order = false<br /> &nbsp;end<br /> end<br /> <br /> if not(is_stop_order) then &nbsp;<br /> &nbsp;if in_trade and count~=0 then --in_trade признак того, что мы в позиции<br /> &nbsp; if count&gt;0 then<br /> &nbsp; &nbsp;send_stop_loss(&quot;B&quot;,count,last_price)--формируем стоп-лосс и выставляем его, вызвав функцию send_stop_loss, last_price --цена последней сделки по стратегии<br /> &nbsp; else<br /> &nbsp; &nbsp;send_stop_loss(&quot;S&quot;,count,last_price)<br /> &nbsp; end<br /> &nbsp;end<br /> &nbsp;return<br /> end<br /> <br /> --А дальше мы вычисляем разницу в ценах, проверяем условие стоп-лосса и, при необходимости перевыставляем его. До этого кода дойдет только в том случае, если у нас уже есть выставленный стоп-лосс:<br /> to_log(&quot;stop_loss_control найден стоп ордер count=&quot;..count)<br /> t_so_item=getItem(&quot;stop_orders&quot;, t_so&#91;1&#93;)<br /> delta_price=0;<br /> <br /> if count&gt;0 then<br /> &nbsp;to_log(&quot;count&gt;0&quot;)<br /> &nbsp;delta_price=p_t&#91;0&#93;.close-t_so_item.condition_price; --condition это состояние, p_t строка 79<br /> &nbsp;l_direction=&quot;B&quot;<br /> else<br /> &nbsp;to_log(&quot;count&lt;=0&quot;)<br /> &nbsp;delta_price=t_so_item.condition_price-p_t&#91;0&#93;.close <br /> &nbsp;l_direction=&quot;S&quot;<br /> end<br /> to_log(&quot;delta_price=&quot;..delta_price..&quot; &nbsp; &nbsp;t_so&#91;0&#93;.qty=&quot;..t_so_item.qty..&quot; &nbsp; &nbsp; &nbsp;p_t&#91;0&#93;.close=&quot;..p_t&#91;0&#93;.close)<br /> <br /> if delta_price&gt;=p_traling_stop_level or count~=t_so_item.qty then<br /> &nbsp;to_log(&quot;Послылаем новую стоп заявку price=&quot;..p_t&#91;0&#93;.close..&quot; количество &quot;..count)<br /> &nbsp;send_stop_loss(l_direction,count,p_t&#91;0&#93;.close)<br /> end<br /> <br />end<br />function Trade(a_oper,a_count,a_price)<br /> if a_count&gt;0 then --Количество сделки<br /> <br /> &nbsp;--Сначала пошлем обычную заявку<br /> &nbsp;t = {<br /> &nbsp; &nbsp;&#91;&quot;CLASSCODE&quot;&#93;=p_classcode, <br /> &nbsp; &nbsp;&#91;&quot;SECCODE&quot;&#93;=p_seccode, <br /> &nbsp; &nbsp;&#91;&quot;ACTION&quot;&#93;=&quot;NEW_ORDER&quot;, <br /> &nbsp; &nbsp;&#91;&quot;ACCOUNT&quot;&#93;=p_account, <br /> &nbsp; &nbsp;&#91;&quot;CLIENT_CODE&quot;&#93;=p_clientcode, <br /> &nbsp; &nbsp;&#91;&quot;TYPE&quot;&#93;=&quot;L&quot;, <br /> &nbsp; &nbsp;&#91;&quot;OPERATION&quot;&#93;=a_oper, <br /> &nbsp; &nbsp;&#91;&quot;QUANTITY&quot;&#93;=tostring(a_count), <br /> &nbsp; &nbsp;&#91;&quot;PRICE&quot;&#93;=tostring(a_price),<br /> &nbsp; &nbsp;&#91;&quot;EXPIRY_DATE&quot;&#93;=&quot;GTC&quot;, <br /> &nbsp; &nbsp;&#91;&quot;TRANS_ID&quot;&#93;=p_TRANS_ID<br /> &nbsp; }<br /> &nbsp;res=sendTransaction(t) <br /> &nbsp;<br /> &nbsp;--заявку послали и сразу же мы оказались в позиции и будем в ней до тех пор, пока не закроется сделка <br /> &nbsp;--или пока не будет доказано обратное (мы узнаем, что сделка не прошла)<br /> &nbsp;in_trade=true <br /> &nbsp;<br /> &nbsp;direction=a_oper--последний тип операции<br /> &nbsp;message(&quot;Количество сделки &quot;..tostring(a_count)..&quot; &nbsp;тип операции &quot;..a_oper..&quot; Цена &quot;..a_price,1)<br /> end<br />end<br />--Обработчик события сделки. <br />function OnTrade(trade) <br /> nord=trade&#91;&quot;order_num&quot;&#93; <br /> price=trade&#91;&quot;price&quot;&#93;<br /> to_log(&quot;Совершена сделка: номер заявки &quot;..tostring(nord)..&quot;; цена &quot;..tostring(price)..&quot;: количество &quot;..tostring(trade&#91;&quot;qty&quot;&#93;))<br /> if nord==order_num then <br /> &nbsp;qty=trade&#91;&quot;qty&quot;&#93; <br /> &nbsp;if direction==&quot;B&quot; then<br /> &nbsp; count=count+qty<br /> &nbsp;else<br /> &nbsp; count=count-qty<br /> &nbsp;end<br /> &nbsp;send_stop_loss(direction,count,price) <br /> &nbsp;last_price=price<br /> end<br />end<br />--Обработчик события создания стоп заявки<br />function OnStopOrder(stop_order) <br /> <br /> <br /> --бит 0 (0x1) Заявка активна, иначе не активна<br /> if stop_order&#91;&quot;order_num&quot;&#93;==stop_loss_num and bit.band(stop_order&#91;&quot;flags&quot;&#93;,0x1)==0x1 then <br /> &nbsp;to_log(&quot;сняли признак что мы в процессе выставления стоп оредра&quot;)<br /> &nbsp;in_set_stop_loss=false<br /> end<br /> <br /> --бит 0 (0x1) Заявка активна, иначе не активна,<br /> --бит 1 (0x2) Заявка снята. Если не установлен и значение бита 0 равно 0, то заявка исполнена <br /> --в этом случае мы считаем, что позция закрыта по стоп лоссу<br /> if stop_order&#91;&quot;order_num&quot;&#93;==stop_loss_num and bit.band(stop_order&#91;&quot;flags&quot;&#93;,0x1)==0x0 and bit.band(stop_order&#91;&quot;flags&quot;&#93;,0x2)==0x0 then --stop_loss_num = &quot;&quot; --номер стоп заявик по открытой сделке<br /> &nbsp;in_set_stop_loss=false<br /> &nbsp;count=0 <br /> end<br />end<br />--Удалить стоп лосс<br />function delete_stop_loss(a_num)<br /> t = {<br /> &nbsp; &#91;&quot;CLASSCODE&quot;&#93;=p_classcode, <br /> &nbsp; &#91;&quot;SECCODE&quot;&#93;=p_seccode, <br /> &nbsp; &#91;&quot;ACTION&quot;&#93;=&quot;KILL_STOP_ORDER&quot;, <br /> &nbsp; &#91;&quot;ACCOUNT&quot;&#93;=p_account, <br /> &nbsp; &#91;&quot;CLIENT_CODE&quot;&#93;=p_clientcode, <br /> &nbsp; &#91;&quot;TYPE&quot;&#93;=&quot;L&quot;, <br /> &nbsp; &#91;&quot;OPERATION&quot;&#93;=l_oper, <br /> &nbsp; &#91;&quot;STOP_ORDER_KIND&quot;&#93;=&quot;SIMPLE_STOP_ORDER&quot;,<br /> &nbsp; &#91;&quot;TRANS_ID&quot;&#93;=p_TRANS_ID_STOP,<br /> &nbsp; &#91;&quot;STOP_ORDER_KEY&quot;&#93;=tostring(a_num)<br /> &nbsp;}<br /> res=sendTransaction(t) <br /> message(&quot;Удаляем стоп лосс: сообщение &quot;..res..&quot;; номер &quot;..a_num,1)<br />end<br />--Послать стоп заявку<br />function send_stop_loss(a_direction,a_count,a_price)<br /> to_log(&quot;send_stop_loss in_set_stop_loss=&quot;..tostring(in_set_stop_loss))<br /> if not(in_set_stop_loss) then<br /> <br /> &nbsp;if stop_loss_num~=&quot;&quot; then <br /> &nbsp; delete_stop_loss(stop_loss_num) <br /> &nbsp;end<br /> <br /> &nbsp;if a_direction==&quot;B&quot; then<br /> &nbsp; l_oper=&quot;S&quot;<br /> &nbsp; l_count=a_count <br /> &nbsp; dir=-1<br /> &nbsp;else<br /> &nbsp; l_oper=&quot;B&quot;<br /> &nbsp; l_count=-a_count<br /> &nbsp; dir=1<br /> &nbsp;end<br /> &nbsp;<br /> &nbsp;l_price=a_price+p_stop_loss_level*dir <br /> &nbsp;if l_count&gt;0 then<br /> &nbsp;<br /> &nbsp; to_log(&quot;send_stop_loss Зашли сюда&quot;,1)<br /> &nbsp; in_set_stop_loss=true<br /> &nbsp;<br /> &nbsp; --Пошлем стоп заявку<br /> &nbsp; t = {<br /> &nbsp; &nbsp; &#91;&quot;CLASSCODE&quot;&#93;=p_classcode, <br /> &nbsp; &nbsp; &#91;&quot;SECCODE&quot;&#93;=p_seccode, <br /> &nbsp; &nbsp; &#91;&quot;ACTION&quot;&#93;=&quot;NEW_STOP_ORDER&quot;, <br /> &nbsp; &nbsp; &#91;&quot;ACCOUNT&quot;&#93;=p_account, <br /> &nbsp; &nbsp; &#91;&quot;CLIENT_CODE&quot;&#93;=p_clientcode, <br /> &nbsp; &nbsp; &#91;&quot;TYPE&quot;&#93;=&quot;L&quot;, <br /> &nbsp; &nbsp; &#91;&quot;OPERATION&quot;&#93;=l_oper, <br /> &nbsp; &nbsp; &#91;&quot;QUANTITY&quot;&#93;=tostring(l_count), <br /> &nbsp; &nbsp; &#91;&quot;PRICE&quot;&#93;=tostring(l_price+p_spread*dir),<br /> &nbsp; &nbsp; &#91;&quot;EXPIRY_DATE&quot;&#93;=&quot;GTC&quot;, <br /> &nbsp; &nbsp; &#91;&quot;STOPPRICE&quot;&#93;=tostring(l_price),<br /> &nbsp; &nbsp; &#91;&quot;STOP_ORDER_KIND&quot;&#93;=&quot;SIMPLE_STOP_ORDER&quot;,<br /> &nbsp; &nbsp; &#91;&quot;TRANS_ID&quot;&#93;=p_TRANS_ID_STOP<br /> &nbsp; &nbsp;}<br /> &nbsp; res=sendTransaction(t) <br /> &nbsp; message(res,1)<br /> &nbsp; to_log(&quot;Выставли стоп заявку &quot;..l_oper)<br /> &nbsp;end<br /> end<br />end<br />--обработка события транзакции<br />function OnTransReply(trans_reply)<br /> id=tostring(trans_reply&#91;&quot;trans_id&quot;&#93;) <br /> <br /> to_log(&quot;Обработка транзакции &quot;..id)<br /> <br /> --если это наша транзакция, обработаем ее<br /> if id==p_TRANS_ID then<br /> &nbsp;nord=trans_reply&#91;&quot;order_num&quot;&#93; <br /> &nbsp;<br /> &nbsp;to_log(&quot;Обработка транзакции номер заявки &quot;..nord)<br /> &nbsp;<br /> &nbsp;--если заявка выставилась - запоминаем ее номер, иначе считаем, что мы не в сделке<br /> &nbsp;if nord==nil or nord==0 or nord==&quot;0&quot; then<br /> &nbsp; message(&quot;Заявка не выставилась &quot;,1)<br /> &nbsp; in_trade=false<br /> &nbsp;else<br /> &nbsp; order_num=nord<br /> &nbsp;end<br /> end<br /> <br /> if id==p_TRANS_ID_STOP then<br /> &nbsp;message(&quot;Сообщение транзакции стоп ордера &quot;..trans_reply&#91;&quot;result_msg&quot;&#93;,1)<br /> &nbsp;nord=trans_reply&#91;&quot;order_num&quot;&#93; --Номер заявки <br /> &nbsp;<br /> &nbsp;--если заявка выставилась - запоминаем ее номер, иначе считаем, что мы закончили выставлять стоп заявку<br /> &nbsp;if nord==nil then<br /> &nbsp; message(&quot;Стоп заявка не выставилась &quot;,1)<br /> &nbsp; in_set_stop_loss=false<br /> &nbsp; stop_loss_num=&quot;&quot;<br /> &nbsp;else<br /> &nbsp; stop_loss_num=nord<br /> &nbsp;end<br /> end <br />end<br />function OnStop(stop_flag) <br /> is_run=false<br /> stop_flag=1<br /> p_file:close();<br />end<br /><br /><br /> </td></tr></tbody></table> <br />
			<i>21.08.2018 11:49:53, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32800/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32800/topic3898/</guid>
			<pubDate>Tue, 21 Aug 2018 11:49:53 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32793/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Добрый день.<br /><br />Выложите свой код. <br />
			<i>21.08.2018 08:24:00, Egor Zaytsev.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32793/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32793/topic3898/</guid>
			<pubDate>Tue, 21 Aug 2018 08:24:00 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32787/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Не так написал, выставить безубыток я смогу (по дельте 1), но для трала нужна дельта2. Как сделать что бы после выставления безубытка дельта1 игнорировалась? <br />
			<i>20.08.2018 17:53:18, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32787/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32787/topic3898/</guid>
			<pubDate>Mon, 20 Aug 2018 17:53:18 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32786/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Если в двух словах то пробую сделать безубыток. У меня есть образец кода с трейлинг-стопом, вот я и пробую что бы после первого стопа ставился безубыток, а далее работал трал. Сложность в том, что не понимаю как сделать чтобы после достижения безубытка выставлялся стоп по дельте (по разнице в цене между первым стопом и текущей ценой), а далее эта дельта была другой. <br />
			<i>20.08.2018 17:11:16, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32786/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32786/topic3898/</guid>
			<pubDate>Mon, 20 Aug 2018 17:11:16 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32784/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Добрый день.<br /><br />Не ясно, какую задачу вы решаете? Вариантов может быть много.<br />Например, хотите снять активную заявку по коду клиента.<br />Условие &quot;если&quot; и &quot;и&quot;, то&quot;<br /><br /> &nbsp; &nbsp;if (client_code==&quot;1&quot;) --в кавычках код клиента<br /> &nbsp; &nbsp;and (bit.band(flags, 0x1) ~= 0) --проверяем что заявка активна<br /> &nbsp; &nbsp;then transaction = {TRANS_ID=&quot;1&quot;, ACTION=&quot;KILL_ORDER&quot;, CLASSCODE=class_code, SECCODE=sec_code, ORDER_KEY=tostring(order_num)}<br /> &nbsp; &nbsp; &nbsp; &nbsp;res = sendTransaction(transaction) --снимаем заявку <br />
			<i>20.08.2018 08:49:49, Egor Zaytsev.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32784/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32784/topic3898/</guid>
			<pubDate>Mon, 20 Aug 2018 08:49:49 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Разделение условий.</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message32780/topic3898/">Разделение условий.</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Добрый день. Такой вопрос: Как разделить условия, вначале выполняется одно, другие игнорируются, а затем другое, а первое игнорируется. То есть первое учитывается только один раз От сделки не зависит. <br />
			<i>19.08.2018 18:50:22, vit10052.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message32780/topic3898/</link>
			<guid>http://forum.quik.ru/messages/forum10/message32780/topic3898/</guid>
			<pubDate>Sun, 19 Aug 2018 18:50:22 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
	</channel>
</rss>
