Список форумов AmiSite.ru AmiSite.ru
Форум по Ами
 FAQ  •  Поиск  •  Пользователи  •  Группы   •  Регистрация  •  Профиль  •  Войти и проверить личные сообщения  •  Вход
 Не получается подсчитать число баров Следующая тема
Предыдущая тема
Начать новую тему  Ответить на тему
Автор Сообщение
rupiter



Зарегистрирован: 16.09.2013
Сообщения: 75

СообщениеДобавлено: Ср Мар 09, 2016 12:46 pm Ответить с цитатой Вернуться к началу

Здравствуйте,

AFL - это не язык, а кошмар какой-то.

Пишу простую программу:

Код:

count = 0;

for( i = 0; i < BarCount; i++ )
{
  count += 1;
}


Plot(count, "count", colorBlue, styleDashed);



То есть, первоначально инициализирую переменную count со значением 0 (я так понимаю, что это массив, и переменные - не массивы создавать вообще невозможно?). Далее, на каждом баре значение переменной увеличивается на один (то есть, переинициализируется весь массив с новым значением). По идее, в итоге, должна получиться прямая горизонтальная линия, величиной BarCount. Но она почему-то меняется в зависимости от зума графика. Причем эта величина не равна количеству баров, отображенных на экране - я увеличил масштаб графика так, чтобы отобразилось только 20 последний баров, а индикатор показывал в это время 50 Confused
Посмотреть профиль Отправить личное сообщение
000
Site Admin


Зарегистрирован: 10.12.2007
Сообщения: 9106

СообщениеДобавлено: Ср Мар 09, 2016 2:02 pm Ответить с цитатой Вернуться к началу

Добавь в начало кода строку
Код:
SetBarsRequired(sbrAll, sbrAll);


Ами он дофига умный и не видит необходимости пересчитывать все бары пока их не видно. Считает только видимые и еще берет небольшой запас. Запас меняет в зависимости от кода.

_________________
ceterum censeo carthaginem esse delendam
Удачи. Олег.
Посмотреть профиль Отправить личное сообщение Посетить сайт автора
rupiter



Зарегистрирован: 16.09.2013
Сообщения: 75

СообщениеДобавлено: Ср Мар 09, 2016 4:10 pm Ответить с цитатой Вернуться к началу

Спасибо, вроде получилось.
Посмотреть профиль Отправить личное сообщение
Astrobiolog



Зарегистрирован: 27.01.2013
Сообщения: 66

СообщениеДобавлено: Ср Мар 09, 2016 7:12 pm Ответить с цитатой Вернуться к началу

rupiter писал(а):
Здравствуйте,

AFL - это не язык, а кошмар какой-то.


))))))) AFL становится не кошмаром, а удовольствием, когда знаешь "все его трещинки".
Посмотреть профиль Отправить личное сообщение
trashfx



Зарегистрирован: 27.06.2015
Сообщения: 90

СообщениеДобавлено: Чт Мар 10, 2016 3:15 am Ответить с цитатой Вернуться к началу

rupiter писал(а):
Здравствуйте,

AFL - это не язык, а кошмар какой-то.

Пишу простую программу:

Код:

count = 0;

for( i = 0; i < BarCount; i++ )
{
  count += 1;
}


Plot(count, "count", colorBlue, styleDashed);



То есть, первоначально инициализирую переменную count со значением 0 (я так понимаю, что это массив, и переменные - не массивы создавать вообще невозможно?). Далее, на каждом баре значение переменной увеличивается на один (то есть, переинициализируется весь массив с новым значением). По идее, в итоге, должна получиться прямая горизонтальная линия, величиной BarCount. Но она почему-то меняется в зависимости от зума графика. Причем эта величина не равна количеству баров, отображенных на экране - я увеличил масштаб графика так, чтобы отобразилось только 20 последний баров, а индикатор показывал в это время 50 Confused



A bad worksman always blames his tools!
Посмотреть профиль Отправить личное сообщение
trashfx



Зарегистрирован: 27.06.2015
Сообщения: 90

СообщениеДобавлено: Чт Мар 10, 2016 3:20 am Ответить с цитатой Вернуться к началу

000 писал(а):
Добавь в начало кода строку
Код:
SetBarsRequired(sbrAll, sbrAll);


Ами он дофига умный и не видит необходимости пересчитывать все бары пока их не видно. Считает только видимые и еще берет небольшой запас. Запас меняет в зависимости от кода.


SetBarsRequired( sbrall ) just for getting the number of bars if QuickAFL is on? Are you serious? Loop just for getting entire number of bars of array? Are you guys serious? It seems you all have not much of a clue.

Simply use Status( "QuickAflLastDataBar" );

Код:
ldb = Status( "quickafllastdatabar" );
count = ldb + 1;
Plot(count, "count", colorBlue, styleDashed);
Посмотреть профиль Отправить личное сообщение
trashfx



Зарегистрирован: 27.06.2015
Сообщения: 90

СообщениеДобавлено: Чт Мар 10, 2016 3:26 am Ответить с цитатой Вернуться к началу

trashfx писал(а):
000 писал(а):
Добавь в начало кода строку
Код:
SetBarsRequired(sbrAll, sbrAll);


Ами он дофига умный и не видит необходимости пересчитывать все бары пока их не видно. Считает только видимые и еще берет небольшой запас. Запас меняет в зависимости от кода.


SetBarsRequired( sbrall ) just for getting the number of bars if QuickAFL is on? Are you serious? Loop just for getting entire number of bars of array? Are you guys serious? It seems you all have not much of a clue.

Simply use Status( "QuickAflLastDataBar" );

Код:
ldb = Status( "quickafllastdatabar" );
count = ldb + 1;
Plot(count, "count", colorBlue, styleDashed);



BTW of course there also exist quickaflfirstdatabar

So what if we want to get barindex of entire array if quickafl is turned on?

We do like so

Код:

bi = BarIndex();
fdb = Status( "quickaflfirstdatabar" );
fdbbi = fdb + bi; // this is an array now


printf( "\nBarIndex (bi): %g idx", bi );
printf( "\nQuickAFL first data bar + bi: %g idx", fdbbi );

printf( "\n\nLastValue(bi): %g idx", LastValue(bi) );
printf( "\nQuickAFL first data bar + LastValue(bi): %g idx", LastValue(fdbbi) );



Now stop crying and stop being bad workmen crying out loud. It's pathetic.
Посмотреть профиль Отправить личное сообщение
rupiter



Зарегистрирован: 16.09.2013
Сообщения: 75

СообщениеДобавлено: Чт Мар 10, 2016 8:08 am Ответить с цитатой Вернуться к началу

Astrobiolog писал(а):
rupiter писал(а):
Здравствуйте,

AFL - это не язык, а кошмар какой-то.


))))))) AFL становится не кошмаром, а удовольствием, когда знаешь "все его трещинки".

Ну, если только "все трещинки". Я вот до такой степени знаю EasyLanguage и сейчас, сидя на Амиброкере, работаю и плачу)).
Посмотреть профиль Отправить личное сообщение
rupiter



Зарегистрирован: 16.09.2013
Сообщения: 75

СообщениеДобавлено: Чт Мар 10, 2016 8:15 am Ответить с цитатой Вернуться к началу

trashfx писал(а):

Now stop crying and stop being bad workmen crying out loud. It's pathetic.
Nobody's crying (not yet at least Very Happy ). I've never said I was too proficient with Amibroker. But comparing with TradeStation it's obvious that Amibroker is a way less user-friendly.
Посмотреть профиль Отправить личное сообщение
rupiter



Зарегистрирован: 16.09.2013
Сообщения: 75

СообщениеДобавлено: Чт Мар 10, 2016 8:34 am Ответить с цитатой Вернуться к началу

trashfx писал(а):

A bad worksman always blames his tools!

Ok. There is a very useful EL function called "Marketposition". It shows if you are currently flat or in a long or short position. While being on TS I used it almost in every strategy... Then I found out that there was no such thing in Amibroker. Whom should I blame that Amibroker has no such essential tool?
Посмотреть профиль Отправить личное сообщение
000
Site Admin


Зарегистрирован: 10.12.2007
Сообщения: 9106

СообщениеДобавлено: Чт Мар 10, 2016 9:19 am Ответить с цитатой Вернуться к началу

В Ами есть возможность отслеживать в позиции или "квадратный".
Посмотри в хелпере "Porfolio Backtester Interface Reference Guide". Ну и заодно, чтобы не вставать 2 раза "Portfolio-level backtesting" Smile

_________________
ceterum censeo carthaginem esse delendam
Удачи. Олег.
Посмотреть профиль Отправить личное сообщение Посетить сайт автора
000
Site Admin


Зарегистрирован: 10.12.2007
Сообщения: 9106

СообщениеДобавлено: Чт Мар 10, 2016 9:23 am Ответить с цитатой Вернуться к началу

trashfx писал(а):


SetBarsRequired( sbrall ) just for getting the number of bars if QuickAFL is on? Are you serious?

He didn't need to count the number of bars. He had to understand why this result. He didn't know about QuickAFL.

_________________
ceterum censeo carthaginem esse delendam
Удачи. Олег.
Посмотреть профиль Отправить личное сообщение Посетить сайт автора
trashfx



Зарегистрирован: 27.06.2015
Сообщения: 90

СообщениеДобавлено: Чт Мар 10, 2016 2:31 pm Ответить с цитатой Вернуться к началу

rupiter писал(а):
trashfx писал(а):

A bad worksman always blames his tools!

Ok. There is a very useful EL function called "Marketposition". It shows if you are currently flat or in a long or short position. While being on TS I used it almost in every strategy... Then I found out that there was no such thing in Amibroker. Whom should I blame that Amibroker has no such essential tool?


It is pretty obvious that you are just incompetent otherwise you would not come up with such BS.

From some other forum:

Цитата:
I politely ask, perhaps you can show me sample AFL code I need to put into a System that will allow me to detect when I'm in a trade.
I just updated my Amibroker to the latest version and still cannot find a reference.

Using Multicharts as an Example :

Код:
If MarketPosition = 0 AND BuySetup then   // No current position but we do have a Buy Setup
    Buy ("LE") 3 contracts next bar at (high + PointSize) stop;  // This may or may not get filled on the next bar
   
// Long Initial Stops   
If MarketPosition > 0 AND barssinceentry = 0 then
    InitialStop = Low[1] ;
If MarketPosition > 0 AND barssinceentry > 0 then
    Sell ("L_IS") next bar at InitialStop stop;

If MarketPosition = 3 AND Close > EntryPrice+5 then
    Sell ("PT1_IS") 1 contracts this bar at Market;

If MarketPosition >= 2 AND Close > EntryPrice+10 then
    Sell ("PT2_IS") 2 contracts this bar at Market;



MarketPosition is an internal variable that displays the number of contracts/shares that we are long or short.
It is maintained by MC.
Using the above example, if after 5 ticks profit, I decide to Sell 1 contract, MarketPosition would now = 2.
Again MC automatically maintains how many contracts I have remaining in my position.
[...]
What is the AFL System code for AB to do this style of thing ???

Neil.


Response by AB developer:

Цитата:
AmiBroker code for that (that is one of many possible implementations) is:


Код:
Buy = BuySetup;
Sell = 0; // sell is via stops
SetPositionSize( 3, spsShares ); // 3 contracts entry
ApplyStop( stopTypeLoss, stopModePoint, BuyPrice - Ref( Low, -1 ), 0 );
 
SetCustomBacktestProc("");
if( Status("action") == actionPortfolio )
{
   bo = GetBacktesterObject();
 
   bo.PreProcess(); // Initialize backtester
 
   for( bar=0; bar < BarCount; bar++)
   {
    bo.ProcessTradeSignals( bar );
 
    for( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )
    {
      Contracts = pos.Shares;
      Closeprice = pos.GetPrice( bar, "C" );

      if( Contracts == 3 AND Closeprice > pos.EntryPrice + 5 )
           bo.ScaleTrade( bar, pos.Symbol, False, Closeprice, Closeprice );

      if( Contracts >=2 AND Closeprice > pos.EntryPrice + 10 )
           bo.ScaleTrade( bar, pos.Symbol, False, Closeprice, 2 * Closeprice );
     }
    }
   bo.PostProcess(); // Finalize backtester
}



AmiBroker portfolio backtester maintains the LIST of positions (not just one variable as TS/MC), as it can open multiple positions on multiple symbols and tracks all of them. The list of open positions is accessible from the formula level via GetFirstOpenPos/GetNextOpenPos as shown in the code above. This way you get the access to the Trade object that has IsLong/IsShort methods to detect whenever you are currently long or short on given position, you can query current position value, size (number of shares/contracts), you can scale positions up/down and do everything imaginable.
AmiBroker backtester interface is object oriented and what may initially look as a little more complex stuff to write gives you infinite flexibility at the end of the day. The problem with Tradestation/MC Easylanguage is that it is "easy" only at the beginning, at some point you hit the wall of either something being not realizable or running way too slow to be usable or simply blowing up entire app because you run out of resources. Try running backtest on whole universe of US markets (8000+ symbols) or do some advanced sorting/ranking/rebalancing systems and then you will know what I am talking about. But of course there are many traders out there and different trading methodologies. For traders who trade 1 or 2 instruments only and some simple strategies Easylanguage may look good. AmiBroker serves different purpose - it is mainly advanced system development platform for quantitative system traders.

If you have any future questions/comments please contact our technical support : support at amibroker dot com because quite frankly I am very busy and I don't have time to spend on forums as I would rather spend free time with my family or improving the software that I use by myself for trading and system design.

Thank you for listening and happy trading.

Tomasz Janeczko
amibroker.com



Tomasz Janezko писал(а):
.... the "MarketPosition" variable that this guy was talking about is TS legacy and a source of problems because it is NOT compatible with portfolio backtesting.

With AmiBroker, you can change the sizes of postions based on sizes of OTHER postions on OTHER symbols (see rebalancing example),
with "MarketPosition" being limited to current (one and only one) symbol, it is simply not possible to do.

http://www.amibroker.com/kb/2006/03/06/re-balancing-open-positions/

Bottom line, the "MarketPosition" variable that the MC user is so delighted is a LIMITATION, not a good thing.


and


Tomasz Janezko писал(а):
The paramount difference between AmiBroker and MC code is that AmiBroker code above handles PORTFOLIO.
It works on multiple-symbol portfolios, not only single symbol and positions are tracked for each symbol separately (each Trade object has "Symbol" property)

As written here:
http://www.amibroker.com/guide/a_custombacktest.html

every open position is tracked AND CAN BE QUERIED from formula level for any information listed below.

Such easy things can be of course written in almost any platform.
Troubles with MC start, when you try to do some more tricky things.
Ask them about rotational trading systems and rebalancing like this:
http://www.amibroker.com/kb/2006/03/06/re-balancing-open-positions/


Последний раз редактировалось: trashfx (Чт Мар 10, 2016 2:35 pm), всего редактировалось 1 раз
Посмотреть профиль Отправить личное сообщение
trashfx



Зарегистрирован: 27.06.2015
Сообщения: 90

СообщениеДобавлено: Чт Мар 10, 2016 2:33 pm Ответить с цитатой Вернуться к началу

000 писал(а):
trashfx писал(а):


SetBarsRequired( sbrall ) just for getting the number of bars if QuickAFL is on? Are you serious?

He didn't need to count the number of bars. He had to understand why this result. He didn't know about QuickAFL.


Then he should read about it but not start crying and talking newbie BS.

http://www.amibroker.com/guide/h_understandafl.html
http://www.amibroker.com/kb/2008/07/03/quickafl/
Посмотреть профиль Отправить личное сообщение
trashfx



Зарегистрирован: 27.06.2015
Сообщения: 90

СообщениеДобавлено: Чт Мар 10, 2016 2:34 pm Ответить с цитатой Вернуться к началу

rupiter писал(а):

I've never said I was too proficient with Amibroker. But comparing with TradeStation it's obvious that Amibroker is a way less user-friendly.


Then rather stfu instead of talking about things you have no clue about. Or continue using limited TS instead. Easy.
Посмотреть профиль Отправить личное сообщение
Показать сообщения:      
Начать новую тему  Ответить на тему


 Перейти:   



Следующая тема
Предыдущая тема
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете вкладывать файлы
Вы не можете скачивать файлы


Powered by phpBB © 2001, 2002 phpBB Group :: FI Theme :: Часовой пояс: GMT + 3

File Attachment © by Meik Sievertsen