<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Форум QUIK [тема: Не срабатывает  while Run and trans_Status == nil do sleep(1); end;]</title>
		<link>http://forum.quik.ru</link>
		<description>Новое в теме Не срабатывает  while Run and trans_Status == nil do sleep(1); end; форума  на сайте Форум QUIK [forum.quik.ru]</description>
		<language>ru</language>
		<docs>http://backend.userland.com/rss2</docs>
		<pubDate>Sun, 03 May 2026 12:40:38 +0300</pubDate>
		<item>
			<title>Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message24840/topic2829/">Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Врятли. Но дебагер говорил что с кодом все нормально. &nbsp; <br />
			<i>24.05.2017 18:45:22, kvazar1988.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message24840/topic2829/</link>
			<guid>http://forum.quik.ru/messages/forum10/message24840/topic2829/</guid>
			<pubDate>Wed, 24 May 2017 18:45:22 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message24839/topic2829/">Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<br />====quote====<br /><a class="blog-p-user-name" id="bp_aqU55lmu" href="/user/4532/" bx-tooltip-user-id="4532">kvazar1988</a> написал:<br />Я ее частично позаимствовал. И где то она зацикливается при покупке и начинает бесконечно &nbsp;покупать...<br />=============<br />Тогда Вы не совсем правильно задали вопрос в теме.<br />--------------------------------<br />Правильно получается так:<br />-------------------------<br />&quot;Почему эта программа где то зацикливается при покупке и начинает бесконечно &nbsp;покупать.&quot;<br />----------------------------<br />Чтобы ответить на этот вопрос надо сделать следующее:<br />1) восстановить алгоритм по тексту<br />2) поставить отладочную печать<br />3) сравнить результаты в файле отладки с алгоритмом и найти ошибку, а может быть и не одну.<br />--------------------<br />Как думаете, кто-нибудь, кроме Вас, будет это делать?<br />========================= <br />
			<i>24.05.2017 18:33:31, Николай  Камынин.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message24839/topic2829/</link>
			<guid>http://forum.quik.ru/messages/forum10/message24839/topic2829/</guid>
			<pubDate>Wed, 24 May 2017 18:33:31 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message24838/topic2829/">Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Я ее частично позаимствовал. И где то она зацикливается при покупке и начинает бесконечно &nbsp;покупать... <br />
			<i>24.05.2017 18:15:23, kvazar1988.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message24838/topic2829/</link>
			<guid>http://forum.quik.ru/messages/forum10/message24838/topic2829/</guid>
			<pubDate>Wed, 24 May 2017 18:15:23 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message24833/topic2829/">Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			<noindex><a href="https://forum.quik.ru/user/4532/" target="_blank" rel="nofollow">kvazar1988</a></noindex><br />Правильно ли я понял, что эту программу написали &nbsp;не Вы? <br />
			<i>24.05.2017 16:29:05, Николай  Камынин.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message24833/topic2829/</link>
			<guid>http://forum.quik.ru/messages/forum10/message24833/topic2829/</guid>
			<pubDate>Wed, 24 May 2017 16:29:05 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
		<item>
			<title>Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</title>
			<description><![CDATA[<b><a href="http://forum.quik.ru/messages/forum10/message24832/topic2829/">Не срабатывает  while Run and trans_Status == nil do sleep(1); end;</a></b> в форуме <a href="http://forum.quik.ru/forum10/">Программирование на языке Lua</a>. <br />
			Здравствуйте. В коде не срабатывает &nbsp;while Run and trans_Status == nil do sleep(1); end; <br />Скажите пожалуйста как исправить или иначе написать.<br />--&#91;&#91;<br />&#93;&#93;<br /><br />--/*НАСТРАИВАЕМЫЕ ПАРАМЕТРЫ*/<br />--ACCOUNT &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = 'NL0011100043'; &nbsp; &nbsp; &nbsp; -- Идентификатор счета<br />ACCOUNT &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = 'SPBFUT0026E'; &nbsp; &nbsp; &nbsp; &nbsp;-- Идентификатор счета<br />--CLASS_CODE &nbsp; &nbsp; &nbsp; &nbsp;= 'QJSIM'; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Код класса<br />CLASS_CODE &nbsp; &nbsp; &nbsp; &nbsp;= 'SPBFUT'; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Код класса<br />--SEC_CODE &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= 'SBER'; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Код бумаги<br />SEC_CODE &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= 'SiM7'; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Код бумаги<br />NPos=2 &nbsp; --размер открываемых позиций одной сделкой<br />Price1=&quot;PRICE&quot; &nbsp;--ссылка на график цены<br />ParMed1=&quot;SMA1&quot; &nbsp; &nbsp; --синий, ссылка на график<br /><br /><br />INTERVAL &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= INTERVAL_M1; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Таймфрейм графика (для построения скользящих)<br /><br />--/*РАБОЧИЕ ПЕРЕМЕННЫЕ РОБОТА (менять не нужно)*/<br />SEC_PRICE_STEP &nbsp; &nbsp;= 0; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- ШАГ ЦЕНЫ ИНСТРУМЕНТА<br />SEC_NO_SHORT &nbsp; &nbsp; &nbsp;= false; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Флаг, что по данному инструменту запрещены операции шорт<br />DS &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= nil; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Источник данных графика (DataSource)<br />ROBOT_STATE &nbsp; &nbsp; &nbsp; ='В ПОИСКЕ ТОЧКИ ВХОДА';-- СОСТОЯНИЕ робота &#91;'В ПРОЦЕССЕ СДЕЛКИ', либо 'В ПОИСКЕ ТОЧКИ ВХОДА'&#93;<br />trans_id &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= os.time(); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Задает начальный номер ID транзакций<br />trans_Status &nbsp; &nbsp; &nbsp;= nil; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Статус текущей транзакции из функции OnTransPeply<br />trans_result_msg &nbsp;= ''; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Сообщение по текущей транзакции из функции OnTransPeply<br />CurrentDirect &nbsp; &nbsp; = 'BUY'; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Текущее НАПРАВЛЕНИЕ &#91;'BUY', или 'SELL'&#93;<br />LastOpenBarIndex &nbsp;= &nbsp;0; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Индекс свечи, на которой была открыта последняя позиция (нужен для того, чтобы после закрытия по стопу тут же не открыть еще одну позицию)<br />Run &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = true; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Флаг поддержания работы бесконечного цикла в main<br />Napravlenie_Sdelki=false --направление открытия позиции &nbsp;,Napravlenie_Sdelki='ПОЗИЯ КУПЛЕНА, ОТКРЫТА' &nbsp; Napravlenie_Sdelki='ПОЗИЯ ПРОДАНА, ОТКРЫТА'<br /><br /><br />function crossOverMed() &nbsp; --функция пересечения<br />if &nbsp;tPrice1&#91;0&#93;.close&lt;tPrice2&#91;0&#93;.close and tPrice1&#91;1&#93;.close&gt;tPrice2&#91;1&#93;.close &nbsp; &nbsp;then<br /> &nbsp; &nbsp; return true<br />	 else return false<br />end<br />end<br /><br />function crossUnderMed() &nbsp; --функция пресечения<br />if &nbsp;tPrice1&#91;0&#93;.close&gt;tPrice2&#91;0&#93;.close and tPrice1&#91;1&#93;.close&lt;tPrice2&#91;1&#93;.close &nbsp; &nbsp;then<br /> &nbsp; &nbsp; return true<br />	 else return false<br />end<br />end<br /><br /><br /><br /><br /><br />-- Функция первичной инициализации скрипта (ВЫЗЫВАЕТСЯ ТЕРМИНАЛОМ QUIK в самом начале)<br />function OnInit()<br /> &nbsp; -- Получает доступ к свечам графика<br /> &nbsp; local Error = '';<br /> &nbsp; DS,Error = CreateDataSource(CLASS_CODE, SEC_CODE, INTERVAL);<br /> &nbsp; -- Проверка<br /> &nbsp; if DS == nil then<br /> &nbsp; &nbsp; &nbsp;message('Простой MA-робот:ОШИБКА получения доступа к свечам! '..Error);<br /> &nbsp; &nbsp; &nbsp;-- Завершает выполнение скрипта<br /> &nbsp; &nbsp; &nbsp;Run = false;<br /> &nbsp; &nbsp; &nbsp;return;<br /> &nbsp; end;<br /><br /> &nbsp; -- Получает ШАГ ЦЕНЫ ИНСТРУМЕНТА<br /> &nbsp; SEC_PRICE_STEP = getParamEx(CLASS_CODE, SEC_CODE, &quot;SEC_PRICE_STEP&quot;).param_value;<br />end;<br /><br />function main()<br /> &nbsp; -- Выводит сообщение<br /> &nbsp; message('Простой MA-робот: '..ROBOT_STATE);<br /> &nbsp; -- &quot;Бесконечный&quot; цикл<br /> &nbsp; while Run do<br /> &nbsp; NumCandles1=getNumCandles(Price1)<br /> &nbsp; NumCandles2=getNumCandles(ParMed1)<br /><br /> &nbsp; &nbsp; tPrice1,n1,s1 = getCandlesByIndex (Price1, 0, NumCandles1-2, 2) &nbsp; --считывает данные с графика цены<br /> &nbsp; &nbsp; tPrice2,n2,s2 = getCandlesByIndex (ParMed1, 0, NumCandles2-2, 2) &nbsp;--считывает данные с графика сма<br /><br /><br />	 &nbsp;---------------------------------------------------------------------------------------------------------------------------------------------------------------------<br />	 &nbsp;--механизм открытия позиции<br />	 &nbsp;---------------------------------------------------------------------------------------------------------------------------------------------------------------------<br /><br />	 &nbsp;--Если СОСТОЯНИЕ робота &quot;В ПРОЦЕССЕ СДЕЛКИ&quot;<br /> &nbsp; &nbsp; &nbsp;if ROBOT_STATE == 'В ПРОЦЕССЕ СДЕЛКИ' then<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Выводит сообщение<br /> &nbsp; &nbsp; &nbsp; &nbsp; message('Робот: В ПРОЦЕССЕ СДЕЛКИ');<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Делает 10 попыток открыть сделку<br /> &nbsp; &nbsp; &nbsp; &nbsp; local Price = false; -- Переменная для получения результата открытия позиции (цена, либо ошибка(false))<br /> &nbsp; &nbsp; &nbsp; &nbsp; for i=1,10 do<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if not Run then return; end; -- Если скрипт останавливается, не затягивает процесс<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Если первый раз пытается открыть SELL, а операции шорт по данному инструменту запрещены<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if CurrentDirect == &quot;SELL&quot; and SEC_NO_SHORT then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Прерывает цикл FOR<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Совершает СДЕЛКУ указанного типа &#91;&quot;BUY&quot;, или &quot;SELL&quot;&#93; по рыночной(текущей) цене размером в 1 лот,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--- возвращает цену открытой сделки, либо FALSE, если невозможно открыть сделку<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Price = Trade(CurrentDirect);<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Если сделка открылась<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if Price ~= false then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Прерывает цикл FOR<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sleep(100); -- Пауза в 100 мс между попытками открыть сделку<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; if not Run then return; end; -- Если скрипт останавливается, не затягивает процесс<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Если сделка открыта<br /> &nbsp; &nbsp; &nbsp; &nbsp; if Price ~= false then<br />		 ROBOT_STATE = 'ОТКРЫЛ ПОЗИЦИЮ №1'<br />		 message('Робот: ОТКРЫЛ ПОЗИЦИЮ №1');<br /> &nbsp; &nbsp; &nbsp; &nbsp;end;<br />---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br />--откоытие позиции<br />---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br /> &nbsp; &nbsp; &nbsp;else<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- СОСТОЯНИЕ робота 'В ПОИСКЕ ТОЧКИ ВХОДА'<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Если на этой свече еще не было открыто позиций<br /> &nbsp; &nbsp; &nbsp; &nbsp; if DS:Size() &gt; LastOpenBarIndex then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Если быстрая пересекла медленную СНИЗУ ВВЕРХ<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- if FastMA(DS:Size()-1) &lt;= SlowMA(DS:Size()-1) and FastMA() &gt; SlowMA() then<br />		 &nbsp; if crossOverMed() and ROBOT_STATE == 'В ПОИСКЕ ТОЧКИ ВХОДА' then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Задает направление НА ПОКУПКУ<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CurrentDirect = 'BUY';<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message('CurrentDirect = &quot;BUY&quot;');<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Меняет СОСТОЯНИЕ робота на &quot;В ПРОЦЕССЕ СДЕЛКИ&quot;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ROBOT_STATE = 'В ПРОЦЕССЕ СДЕЛКИ';<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Если быстрая пересекла медленную СВЕРХУ ВНИЗ<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;elseif &nbsp; &nbsp; &nbsp; &nbsp; crossUnderMed() and ROBOT_STATE == 'В ПОИСКЕ ТОЧКИ ВХОДА' then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- Если по данному инструменту не запрещены операции шорт<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not SEC_NO_SHORT then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Задает направление НА ПРОДАЖУ<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;CurrentDirect = 'SELL';<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;message('CurrentDirect = &quot;SELL&quot;');<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Меняет СОСТОЯНИЕ робота на &quot;В ПРОЦЕССЕ СДЕЛКИ&quot;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ROBOT_STATE = 'В ПРОЦЕССЕ СДЕЛКИ';<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp;end;<br /><br /> &nbsp; &nbsp; &nbsp;sleep(10);--Пауза 10 мс, для того, чтобы не перегружать процессор компьютера<br /> &nbsp; end;<br />end;<br /><br />-- Функция вызывается терминалом QUIK при получении ответа на транзакцию пользователя<br />function OnTransReply(trans_reply)<br /> &nbsp; -- Если поступила информация по текущей транзакции<br /> &nbsp; if trans_reply.trans_id == trans_id then<br /> &nbsp; &nbsp; &nbsp;-- Передает статус в глобальную переменную<br /> &nbsp; &nbsp; &nbsp;trans_Status = trans_reply.status;<br /> &nbsp; &nbsp; &nbsp;-- Передает сообщение в глобальную переменную<br /> &nbsp; &nbsp; &nbsp;trans_result_msg &nbsp;= trans_reply.result_msg;<br />	 &nbsp;message('Робот: trans_Status '..trans_Status..' trans_result_msg '..trans_result_msg);<br /> &nbsp; end;<br />end;<br /><br />-- Функция ВЫЗЫВАЕТСЯ ТЕРМИНАЛОМ QUIK при остановке скрипта<br />function OnStop()<br /> &nbsp; Run = false;<br />end;<br /><br />-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br />-- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ --<br />-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br /><br />-- Совершает СДЕЛКУ указанного типа (Type) &#91;&quot;BUY&quot;, или &quot;SELL&quot;&#93; по рыночной(текущей) цене размером в 1 лот,<br />--- возвращает цену открытой сделки, либо FALSE, если невозможно открыть сделку<br />function Trade(Type)<br /> &nbsp; --Получает ID транзакции<br /> &nbsp; trans_id = trans_id + 1;<br /><br /> &nbsp; local Price = 0;<br /> &nbsp; local Operation = '';<br /> &nbsp; --Устанавливает цену и операцию, в зависимости от типа сделки и от класса инструмента<br /> &nbsp; if Type == 'BUY' then<br /> &nbsp; &nbsp; &nbsp;if CLASS_CODE ~= 'QJSIM' and CLASS_CODE ~= 'TQBR' then Price = getParamEx(CLASS_CODE, SEC_CODE, 'offer').param_value + 10*SEC_PRICE_STEP;end; -- по цене, завышенной на 10 мин. шагов цены<br /> &nbsp; &nbsp; &nbsp;Operation = 'B';<br /> &nbsp; else<br /> &nbsp; &nbsp; &nbsp;if CLASS_CODE ~= 'QJSIM' and CLASS_CODE ~= 'TQBR' then Price = getParamEx(CLASS_CODE, SEC_CODE, 'bid').param_value - 10*SEC_PRICE_STEP;end; -- по цене, заниженной на 10 мин. шагов цены<br /> &nbsp; &nbsp; &nbsp;Operation = 'S';<br /> &nbsp; end;<br /> &nbsp; -- Заполняет структуру для отправки транзакции<br /> &nbsp; local Transaction={<br /> &nbsp; &nbsp; &nbsp;&#91;'TRANS_ID'&#93; &nbsp; = tostring(trans_id),<br /> &nbsp; &nbsp; &nbsp;&#91;'ACTION'&#93; &nbsp; &nbsp; = 'NEW_ORDER',<br /> &nbsp; &nbsp; &nbsp;&#91;'CLASSCODE'&#93; &nbsp;= CLASS_CODE,<br /> &nbsp; &nbsp; &nbsp;&#91;'SECCODE'&#93; &nbsp; &nbsp;= SEC_CODE,<br /> &nbsp; &nbsp; &nbsp;&#91;'OPERATION'&#93; &nbsp;= Operation, -- операция (&quot;B&quot; - buy, или &quot;S&quot; - sell)<br /> &nbsp; &nbsp; &nbsp;&#91;'TYPE'&#93; &nbsp; &nbsp; &nbsp; = 'M', -- по рынку (MARKET)<br /> &nbsp; &nbsp; &nbsp;&#91;'QUANTITY'&#93; &nbsp; = tostring(NPos), -- количество<br /> &nbsp; &nbsp; &nbsp;&#91;'ACCOUNT'&#93; &nbsp; &nbsp;= ACCOUNT,<br /> &nbsp; &nbsp; &nbsp;&#91;'PRICE'&#93; &nbsp; &nbsp; &nbsp;= tostring(Price),<br /> &nbsp; &nbsp; &nbsp;&#91;'COMMENT'&#93; &nbsp; &nbsp;= 'Простой MA-робот'<br /> &nbsp; }<br /> &nbsp; -- Отправляет транзакцию<br /> &nbsp; sendTransaction(Transaction);<br /> &nbsp; -- Ждет, пока получит статус текущей транзакции (переменные &quot;trans_Status&quot; и &quot;trans_result_msg&quot; заполняются в функции OnTransReply())<br /> &nbsp; while Run and trans_Status == nil do sleep(1); end;<br /> &nbsp; -- Запоминает значение<br /> &nbsp; local Status = trans_Status;<br /> &nbsp; -- Очищает глобальную переменную<br /> &nbsp; trans_Status = nil;<br /> &nbsp; -- Если транзакция не выполнена по какой-то причине<br /> &nbsp; if Status ~= 3 then<br /> &nbsp; &nbsp; &nbsp;-- Если данный инструмент запрещен для операции шорт<br /> &nbsp; &nbsp; &nbsp;if Status == 6 then<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Выводит сообщение<br /> &nbsp; &nbsp; &nbsp; &nbsp; message('Робот: Данный инструмент запрещен для операции шорт!');<br /> &nbsp; &nbsp; &nbsp; &nbsp; SEC_NO_SHORT = true;<br /> &nbsp; &nbsp; &nbsp;else<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Выводит сообщение с ошибкой<br /> &nbsp; &nbsp; &nbsp; &nbsp; message('Робот: Транзакция не прошла!\nОШИБКА: '..trans_result_msg);<br /> &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; &nbsp; &nbsp;-- Возвращает FALSE<br /> &nbsp; &nbsp; &nbsp;return false;<br /> &nbsp; else --Транзакция отправлена<br /> &nbsp; &nbsp; &nbsp;local OrderNum = nil;<br /> &nbsp; &nbsp; &nbsp;--ЖДЕТ пока ЗАЯВКА на ОТКРЫТИЕ сделки будет ИСПОЛНЕНА полностью<br /> &nbsp; &nbsp; &nbsp;--Запоминает время начала в секундах<br /> &nbsp; &nbsp; &nbsp;local BeginTime = os.time();<br /> &nbsp; &nbsp; &nbsp;while Run and OrderNum == nil do<br /> &nbsp; &nbsp; &nbsp; &nbsp; --Перебирает ТАБЛИЦУ ЗАЯВОК<br /> &nbsp; &nbsp; &nbsp; &nbsp; for i=0,getNumberOf('orders')-1 do<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;local order = getItem('orders', i);<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--Если заявка по отправленной транзакции ИСПОЛНЕНА ПОЛНОСТЬЮ<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if order.trans_id == trans_id and order.balance == 0 then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Запоминает номер заявки<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OrderNum &nbsp;= order.order_num;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Прерывает цикл FOR<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; --Если прошло 10 секунд, а заявка не исполнена, значит произошла ошибка<br /> &nbsp; &nbsp; &nbsp; &nbsp; if os.time() - BeginTime &gt; 9 then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Выводит сообщение с ошибкой<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;message('Робот: Прошло 10 секунд, а заявка не исполнена, значит произошла ошибка');<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Возвращает FALSE<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return false;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; sleep(10); -- Пауза 10 мс, чтобы не перегружать процессор компьютера<br /> &nbsp; &nbsp; &nbsp;end;<br /><br /> &nbsp; &nbsp; &nbsp;--ЖДЕТ пока СДЕЛКА ОТКРЫТИЯ позиции будет СОВЕРШЕНА<br /> &nbsp; &nbsp; &nbsp;--Запоминает время начала в секундах<br /> &nbsp; &nbsp; &nbsp;BeginTime = os.time();<br /> &nbsp; &nbsp; &nbsp;while Run do<br /> &nbsp; &nbsp; &nbsp; &nbsp; --Перебирает ТАБЛИЦУ СДЕЛОК<br /> &nbsp; &nbsp; &nbsp; &nbsp; for i=0,getNumberOf('trades')-1 do<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;local trade = getItem('trades', i);<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;--Если сделка по текущей заявке<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if trade.order_num == OrderNum then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --Возвращает фАКТИЧЕСКУЮ ЦЕНУ открытой сделки<br />			 &nbsp; if Type == 'BUY' then Napravlenie_Sdelki='ПОЗИЯ КУПЛЕНА, ОТКРЫТА' elseif Type == 'SELL' then Napravlenie_Sdelki='ПОЗИЯ ПРОДАНА, ОТКРЫТА' end &nbsp;-- флаг направления позиции<br /><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return trade.price;<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; --Если прошло 10 секунд, а сделка не совершена, значит на демо-счете произошла ошибка<br /> &nbsp; &nbsp; &nbsp; &nbsp; if os.time() - BeginTime &gt; 9 then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Выводит сообщение с ошибкой<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;message('Робот: Прошло 10 секунд, а сделка не совершена, значит на демо-счете произошла ошибка');<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Возвращает FALSE<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return false;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; sleep(10); -- Пауза 10 мс, чтобы не перегружать процессор компьютера<br /> &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; end;<br />end;<br /><br />-- ПРИНУДИТЕЛЬНО ЗАКРЫВАЕТ ОТКРЫТУЮ ПОЗИЦИЮ переданного типа (Type) &#91;&quot;BUY&quot;, или &quot;SELL&quot;&#93;<br />function KillPos(Type)<br /> &nbsp; -- Дается 10 попыток<br /> &nbsp; local Count = 0; -- Счетчик попыток<br /> &nbsp; if Type == 'BUY' then<br /> &nbsp; &nbsp; &nbsp;-- Пока скрипт не остановлен и позиция не закрыта<br /> &nbsp; &nbsp; &nbsp;while Run and not Trade('SELL') do -- Открывает SELL, тем самым закрывая BUY, если Trade('SELL') вернет TRUE, цикл прекратится<br /> &nbsp; &nbsp; &nbsp; &nbsp; Count = Count + 1; -- Увеличивает счетчик<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Если за 10 попыток не удалось закрыть позицию<br /> &nbsp; &nbsp; &nbsp; &nbsp; if Count == 10 then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Возвращает NIL<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return nil;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; sleep(100); -- Пауза 100 мс, чтобы изменилась ситуация на сервере<br /> &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; else<br /> &nbsp; &nbsp; &nbsp;-- Пока скрипт не остановлен и позиция не закрыта<br /> &nbsp; &nbsp; &nbsp;while Run and not Trade('BUY') do -- Открывает BUY, тем самым закрывая SELL, если Trade('BUY') вернет TRUE, цикл прекратится<br /> &nbsp; &nbsp; &nbsp; &nbsp; Count = Count + 1; -- Увеличивает счетчик<br /> &nbsp; &nbsp; &nbsp; &nbsp; -- Если за 10 попыток не удалось закрыть позицию<br /> &nbsp; &nbsp; &nbsp; &nbsp; if Count == 10 then<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- Возвращает NIL<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return nil;<br /> &nbsp; &nbsp; &nbsp; &nbsp; end;<br /> &nbsp; &nbsp; &nbsp; &nbsp; sleep(100); -- Пауза 100 мс, чтобы изменилась ситуация на сервере<br /> &nbsp; &nbsp; &nbsp;end;<br /> &nbsp; end;<br /> &nbsp; -- Возвращает TRUE, если удалось принудительно закрыть позицию<br /> &nbsp; return true;<br />end;<br />----- <br />
			<i>24.05.2017 15:56:49, kvazar1988.</i>]]></description>
			<link>http://forum.quik.ru/messages/forum10/message24832/topic2829/</link>
			<guid>http://forum.quik.ru/messages/forum10/message24832/topic2829/</guid>
			<pubDate>Wed, 24 May 2017 15:56:49 +0300</pubDate>
			<category>Программирование на языке Lua</category>
		</item>
	</channel>
</rss>
