NexusFi: Find Your Edge


Home Menu

 





AmiBroker Tiered Position Sizing


Discussion in Platforms and Indicators

Updated
      Top Posters
    1. looks_one occasionallurker with 3 posts (1 thanks)
    2. looks_two dwitkin with 3 posts (0 thanks)
    3. looks_3 superthon with 2 posts (0 thanks)
    4. looks_4 medias with 1 posts (0 thanks)
    1. trending_up 10,328 views
    2. thumb_up 2 thanks given
    3. group 5 followers
    1. forum 9 posts
    2. attach_file 0 attachments




 
Search this Thread

AmiBroker Tiered Position Sizing

  #1 (permalink)
 dwitkin 
Reston, Virginia
 
Experience: Advanced
Platform: ThinkOrSwim, AmiBroker
Broker: ThinkOrSwim, TradeStation
Trading: Metals, Grains
Posts: 7 since Nov 2010
Thanks Given: 18
Thanks Received: 3

I tried this question on the AmiBroker Yahoo group and got no responses, so I thought I'd try it here. I like the idea, speed, and openness of AmiBroker, but for me the documentation and official support channels are not what I'd hope.

In any case, if no one has the answer but is interested in the same thing, I'll probably hire a freelancer to evaluate it for me, so if you let me know your interest I'll post the fix / answer if and when I get it.

--------------

Hello. I've written / aggregated some existing code for position sizing. I'm generally receiving the results I expect, but I have the feeling I've written the code so it runs extremely inefficiently. I'm not a strong coder and don't fully 'get' all of the custom backtest features, so there is a good chance I've not used the right parts of the custom backtester and/or have not ordered things in the best way. With that in mind, I'd appreciate as much specific help as people are willing to
provide.

For context, there is no need to give responses simply pointing me to the standard documentation on the custom backtester. I've tried reading the docs multiple times and gathered what info I could from the Internet, but I guess my coding skills are not strong enough to really 'get' much of it. And yes, I've read all the specific posts I could find on using AmiBroker with custom position sizing and "leveraged" what I could from them given my understanding.

Here's what I'm trying to acheive:
1. Tiered position sizing. I want to be able to vary the position size based on the current equity. For example, when equity is $100,000 to $125,000, the size should be a 1% RISK of total equity. I'm defining risk based on my maximum stop loss, not based on the value of the position.

2. I want to display several custom metrics in the trade log.
Specifically, I want to show: (a) Initial Risk $; (b) R-Multiple for each trade, and (c) Cumulative R multiple.

3. I want to show several custom metrics in the backtest report.
Specifically: (a) Total R; and (b) Average R.

All of the code seems to work, but for a few reasons I think I'm likely getting the results very inefficiently. Also, I may be using outdated/incorrect methods. For example, I read that the PositionSize variable is now outdated but I wasn't clear if the same-named custom backtester method was also outdated, (i.e., I didn't see references to the SetPositionSize option in the context of the custom backtester).

Here's the options I've set and the custom backtester code. Feedback to help me achieve the results more efficiently are appreciated.

 
Code
// -------------------------------------------------------------------------------------

/* Global Options */
SetFormulaName("RLCO v011");                            /*Name of script in backtest report */
SetOption("UseCustomBacktestProc", True );      // Use custom backtester for tiered position sizing
SetBarsRequired(100000,100000);         /* ensures that the charts include all bars AND NOT just those on screen */
SetTradeDelays( 1, 0, 1, 0 );                                 /* DELAY one bar on entry, but not exits */
SetOption( "InitialEquity", 100000 );              /* starting capital */
//SetPositionSize( 350, spsPercentOfEquity );        // Not currently used
PositionSize = -100;                  /* trade size is set in the custom backtest section below. Leave at 100% (-100) here */
SetOption( "AccountMargin", 25);          /* Day trading margin; 25% */
SetOption( "MaxOpenPositions", 1 );       /* Span on control = # of open positions allowed */
SetOption( "PriceBoundChecking", 1 );  /* trade only within the chart bar's price range */
SetOption( "CommissionMode", 2 );      /* set commissions AND costs as $ per trade */
SetOption( "CommissionAmount", 0.00 );    /* commissions AND cost */
SetOption( "UsePrevBarEquityForPosSizing", 1 );   /*set the use of last bar's equity for trade size*/
SetOption( "ActivateStopsImmediately", True);     /* Allow immedate exit */
PositionScore = 100/C;            /*Set priority order for trades when mulitple signals trigger on one bar */

// -----------------------------------------------------------------------------------------------------
/* Custom Backtest Code */
// -----------------------------------------------------------------------------------------------------

/* First we enable custom backtest procedure */
SetCustomBacktestProc("");

PctRiskPerTrade = 01;                    // Risk 1% of total equity per trade

/* Here's the custom backtest procedure */
if( Status("action") == actionPortfolio )
{
     bo = GetBacktesterObject();
// --------------------------------------------------------------------
// Testing tiered position sizing starts here
// --------------------------------------------------------------------
     bo.PreProcess();

for ( bar = 0; bar < BarCount; bar++ )
{
     CurrentPortfolioEquity = bo.Equity;

     for ( sig = bo.GetFirstSignal( bar ); sig; sig = bo.GetNextSignal( bar ) )
     {
         if ( CurrentPortfolioEquity > 125000 )
             sig.PosSize = -300;        //1st Tier

         if ( CurrentPortfolioEquity <= 125000 AND CurrentPortfolioEquity > 100000 )
             sig.PosSize = -200;        //    2nd Tier

         if ( CurrentPortfolioEquity <= 100000 AND CurrentPortfolioEquity > 75000 )
             sig.PosSize = -100;        // 3rd Tier

         if ( CurrentPortfolioEquity <= 75000 )
             sig.PosSize = -50;        // 4th Tier
     }

     bo.ProcessTradeSignals( bar );
}

// --------------------------------------------------------------------
// End Test tiered position sizing
// --------------------------------------------------------------------


     bo.Backtest(1);                     // run default backtest procedure

     // Initialize a few variables used later.
        SumProfitPerRisk =0;
        NumTrades =0;
        CumulativeR =0;
        TotalR =0;

    // Iterate through closed trades.
    for( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
    {
       // Risk is the maximum value we expect to lose on a trade
        Risk = ( PctRiskPerTrade / 100 ) * trade.GetEntryValue();
        RMultiple = trade.GetProfit()/Risk;
        CumulativeR = RMultiple + CumulativeR;

        // Show the initial risk and results in R on the backtest summary / trade log
        trade.AddCustomMetric("Initial Risk $", Risk  );
        trade.AddCustomMetric("R-Multiple", RMultiple  );
        trade.AddCustomMetric("Cumulative R", CumulativeR );

        SumProfitPerRisk = SumProfitPerRisk + RMultiple;
        NumTrades++;
    }

         // expectancy = SumProfitPerRisk / NumTrades;
         AverageR = CumulativeR / NumTrades;
         // bo.AddCustomMetric( "Expectancy Per $ Risked", expectancy );
         bo.AddCustomMetric( "Total R", CumulativeR );
         bo.AddCustomMetric( "Average R", AverageR );
         bo.ListTrades();

}

Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
MC PL editor upgrade
MultiCharts
Exit Strategy
NinjaTrader
Increase in trading performance by 75%
The Elite Circle
Trade idea based off three indicators.
Traders Hideout
REcommedations for programming help
Sierra Chart
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Just another trading journal: PA, Wyckoff & Trends
34 thanks
Tao te Trade: way of the WLD
24 thanks
Bigger Wins or Fewer Losses?
19 thanks
GFIs1 1 DAX trade per day journal
16 thanks
Vinny E-Mini & Algobox Review TRADE ROOM
13 thanks
  #2 (permalink)
 badabingbadaboom 
London/UK
 
Posts: 56 since Apr 2013


dwitkin View Post
I tried this question on the AmiBroker Yahoo group and got no responses, so I thought I'd try it here. I like the idea, speed, and openness of AmiBroker, but for me the documentation and official support channels are not what I'd hope.

In any case, if no one has the answer but is interested in the same thing, I'll probably hire a freelancer to evaluate it for me, so if you let me know your interest I'll post the fix / answer if and when I get it.

I don't know what you expect. It sound like a reproach that no one replied to you (actually out of interest I have searched for your question on their user's forum et voila I have found a reply to your question). Everyone is free to reply or not to reply at any time she/he wants to. In addition official support does not provide free coding. AFAIK their hourly quote is $60. This world is not the world of billions of Mother Theresas. I had to learn how to code myself few years ago including how to code in AFL. So it does not fly to you out of nowhere. You have to start to fly yourself. If you don't wanna fly yourself (because of fear, laziness or other reasons) you need someone who does it for you (at an according quote or for free if there is a kind soul out there). But again if you learn something yourself you make yourself independent from others. Knowledge is power.

Reply With Quote
  #3 (permalink)
superthon
Madrid / Spain
 
Posts: 2 since Apr 2014
Thanks Given: 0
Thanks Received: 0


Hi Dave,

I read your post about Tiered position size in Amibroker.
I would like to know if you finally found the solution to the problem you exposed.

I operate in stocks, risking 1% of the current value of my portfolio in every trade and also calculate risk based on entry-stoploss, and I would like to code a system in order to backtest my strategy.

I also would like to calculate the total porfolio risk that I have open in every moment (as an addition of the individual risks of all opened positions)

I will apreciate whatever help you can provide me with the code.

Thanks in advance

Reply With Quote
  #4 (permalink)
 dwitkin 
Reston, Virginia
 
Experience: Advanced
Platform: ThinkOrSwim, AmiBroker
Broker: ThinkOrSwim, TradeStation
Trading: Metals, Grains
Posts: 7 since Nov 2010
Thanks Given: 18
Thanks Received: 3

Hi superthon.

Unfortunately, what I posted was as far as I got. I'm sure AmiBroker is a powerful and fast program. However, I found the support to be lacking (at least for someone at my level of coding expertise, which is limited) so have abandoned it for other products.



superthon View Post
Hi Dave,

I read your post about Tiered position size in Amibroker.
I would like to know if you finally found the solution to the problem you exposed.

I operate in stocks, risking 1% of the current value of my portfolio in every trade and also calculate risk based on entry-stoploss, and I would like to code a system in order to backtest my strategy.

I also would like to calculate the total porfolio risk that I have open in every moment (as an addition of the individual risks of all opened positions)

I will apreciate whatever help you can provide me with the code.

Thanks in advance


Started this thread Reply With Quote
  #5 (permalink)
 occasionallurker 
London UK
 
Posts: 18 since Mar 2014

As it has already been mentioned here someone had already responded to your post in the official AmiBroker forum back then at same time in 2012. Just looked it up myself using the search function.
Here is the link to it https://www.yahoo.com/
And so far you haven't even responded back yet. Have you even tried that one by touini?

FYI, Amiboker's support channel is [email protected] but not that Yahoo forum which is the official user forum.

Reply With Quote
  #6 (permalink)
superthon
Madrid / Spain
 
Posts: 2 since Apr 2014
Thanks Given: 0
Thanks Received: 0

Thank yo for your answers.

I will give a try to the code you reference and look for customizing it to my needs.

If I can get what I need I will post it here

Reply With Quote
  #7 (permalink)
 dwitkin 
Reston, Virginia
 
Experience: Advanced
Platform: ThinkOrSwim, AmiBroker
Broker: ThinkOrSwim, TradeStation
Trading: Metals, Grains
Posts: 7 since Nov 2010
Thanks Given: 18
Thanks Received: 3

Yes, I tried the solution. I've been in touch w/ Touini many times about it and other things.

And yes, I tried the formal AmiBroker support channel... a number of times. The responses were absolutely useless. And frankly, the type of attitude that comes clearly across in your email is the type of attitude I saw many times on the AmiBroker forums (i.e., if you don't know the answer or can't figure it out, you're the problem) and was one of the reasons I have largely abandoned it for products with a more helpful user base and support network.

I don't have a stake in which program I use, I just want to be able to quickly and easily accomplish what I want to do. I'm sure you've made the right choice for you, which is great.




occasionallurker View Post
As it has already been mentioned here someone had already responded to your post in the official AmiBroker forum back then at same time in 2012. Just looked it up myself using the search function.
Here is the link to it https://www.yahoo.com/
And so far you haven't even responded back yet. Have you even tried that one by touini?

FYI, Amiboker's support channel is [email protected] but not that Yahoo forum which is the official user forum.


Started this thread Reply With Quote
  #8 (permalink)
 
medias's Avatar
 medias 
Karlsruhe, Germany
 
Experience: Advanced
Platform: MultiCharts, AmiBroker
Broker: IB/IQFeed
Trading: Stocks, Emini ES
Posts: 60 since Jul 2009
Thanks Given: 30
Thanks Received: 49


dwitkin View Post
And yes, I tried the formal AmiBroker support channel... a number of times. The responses were absolutely useless. And frankly, the type of attitude that comes clearly across in your email is the type of attitude I saw many times on the AmiBroker forums (i.e., if you don't know the answer or can't figure it out, you're the problem) and was one of the reasons I have largely abandoned it for products with a more helpful user base and support network.



I don't have a stake in which program I use, I just want to be able to quickly and easily accomplish what I want to do. I'm sure you've made the right choice for you, which is great.


I would like to disagree in that point. I made the experience that you get quick answers in the yahoo forum. But first things first: do your homework and learn how to deal with Amibroker. Amibroker is different and powerful. But do not expect other people to solve your problems in detail. You have to learn and dig in deeply. There is no free lunch. Consider reading the books from Howard B. Bandy if you want to learn the advanced topics.
Just my 2 cents.

Reply With Quote
  #9 (permalink)
 occasionallurker 
London UK
 
Posts: 18 since Mar 2014


dwitkin View Post
Yes, I tried the solution. I've been in touch w/ Touini many times about it and other things.

And yes, I tried the formal AmiBroker support channel... a number of times. The responses were absolutely useless. And frankly, the type of attitude that comes clearly across in your email is the type of attitude I saw many times on the AmiBroker forums (i.e., if you don't know the answer or can't figure it out, you're the problem) and was one of the reasons I have largely abandoned it for products with a more helpful user base and support network.

Here is the quote from Amibroker's website about what is included in their free support:



Quoting 
What is included in free support package?

Every registered user receives for free:

- unlimited support for installation issues ( The following are criteria for Installation Support: Single desktop install only. Hardware peripherals must be connected directly to machine via cable. Network installation and network hardware are excluded. The product setup program will not run to completion. Immediately after installation is completed, odd behavior or specific errors are encountered. )
- unlimited support issues for basic usage (charting, help on single AFL functions, ASCII import, Metastock import, setting up data plugin)
- basic programming questions (how to write a loop, how to define user function, etc)

What is not included for free?

- third-party data issues
- third-party plugin issues (we can not help with something we did not write)
- writing formulas on customer request (custom programming)
- debugging customer's code
- debugging / writing DLLs
- help on 3rd party tools
- consultation on C/C++, complex JScript, VBScript programming


Email? What mail? I have never ever sent any mail to you in my whole life! I'm not selling anything and we are not friends so why should I send mails to you?
Attittude? I have just informed you here about the difference of the user forum and their support channel and about what has been responded in the forum! That is called a fact not an attitude.
No helpful userbase? That is what I call a slap in the face of i.e.touini. Wow! That's what I call an unbelievably rude attitude! what a slap in the face of all users who are giving solutions there every day free of charge! Some people seem to live on a neverland ranch expecting others to sit outside just to spend time with them 24 hours a day under a slave rate contract. Because of people like you who expect to be spoon feeded on every step and if they are not turning into Prince "Charming" I am really thinking about to abandon my own efforts there which are taking me my free time.

Reply With Quote
  #10 (permalink)
 occasionallurker 
London UK
 
Posts: 18 since Mar 2014



medias View Post
I would like to disagree in that point. I made the experience that you get quick answers in the yahoo forum. But first things first: do your homework and learn how to deal with Amibroker. Amibroker is different and powerful. But do not expect other people to solve your problems in detail. You have to learn and dig in deeply. There is no free lunch. Consider reading the books from Howard B. Bandy if you want to learn the advanced topics.
Just my 2 cents.

Exactly! I have had to learn many things in my life on my own and still learning. Life is a never ending learning process. Yes, I've got help here and there also but without getting spoon feeded. The final step is up to me. And I am giving back knowledge myself. It is one of the most normal things in the world that a certain price has to be paid most of the time. But just taking, taking, taking is not gonna work anywhere.

Reply With Quote




Last Updated on April 9, 2014


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts