[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [amibroker] Re: How to implement a simple risk management ? Tomasz please read it



PureBytes Links

Trading Reference Links

Yes you are right. As to improving the code - the biggest time consuming parts is calling many times Foreign() inside loops

Best regards,
Tomasz Janeczko
amibroker.com
----- Original Message -----
Sent: Thursday, July 12, 2007 1:39 PM
Subject: Re: [amibroker] Re: How to implement a simple risk management ? Tomasz please read it

Hello Tomasz,
 
thanks for your help !
 
I think i understand it now. I thought that i don't need it because RiskPerContract includes my RiskAtClose which includes the foreign function and is symbol based. But now i understand that RiskPerContract will be overwritten at every bar with the value from the last symbol in the open trades list. Am i right ?
 
Another question: I have seen already that the backtest speed increases significantly when i use the Risk Management.
Do you maybe see clear ways to improve the code, maybe through FindOpenPos() or is it simply normally because AmiBroker must look at every bar for open trades and calculate the risk at every bar on those trades, etc.. ?
 
Regards

 
2007/7/12, Tomasz Janeczko <groups@xxxxxxxxxxxxx>:

Hello,
 
There were examples posted in the past. You don't need custom backtester to do for example
VanTharp-style risk management (placing stops at multiple of ATR() and allocating certain percentage of equity in given trade at the time of the entry).
 
For more complex schemes like scaling out position if risk increases during the trade and scaling in positions when risk
decreases during the trade you indeed need custom backtester.
 
As to the code that you have used, it is easy to modify it to work with multiple symbols.
You need to use dynamic variable names for everything. You were going good path but you need to use dynamic variables
for remaining variables such as RiskPerContract, DiffToMaxRisk

Best regards,
Tomasz Janeczko
amibroker.com
----- Original Message -----
Sent: Thursday, July 12, 2007 10:14 AM
Subject: Re: [amibroker] Re: How to implement a simple risk management ? Tomasz please read it

 
Hello Graham,
 
yes i know and i have printed out and read everything that you mentioned already multiple times.
Unfortunately none of the examples are similar to a risk management. The only example which could be useful to implement a risk management was the rebalance example which i used as my template.
I assume the main difference to my code is that the rebalance example doesn't need information from previous bar open trades. I don't know why, but it seems that the PositionValue that he uses already returns previous bar position value, so he doesn't need to retrieve information from open trades at previous bar.
 
If you take a look at my previous post, about 1-2 days ago i have already implemented everything and through Trace View i can see the correct risk at every bar at every open trade and when the risk is to high it scales out at the next bar. Works fine so far at a single symbol, but now the key problem seems to be anywhere to retrieve the correct values from previous bar open trades. I have used dynamic variables with the symbol name. Maybe you can take a look at my code, i can't figure out the reason myself.
 
Anyway i am still surprised that no one else seems to have such a simple risk management already implemented.
Without it the trade risk could rise and rise, also with a trailing stop and before you realize it you could already risk much more % of equity in real life than you have expected in the backtest, because without custom coding (Trace view) the backtester doesn't show the current open risk. It also doesn't show the portfolio risk.
 
So a nice backtest could end with a system that can't be traded in real life, because no one feels comfortable if the open risk is to high and even higher than expected in the backtest.
 
Another example would be that the equity drops down, so the risk increases also and we should scale out contracts. Without any risk management we can't see such situations in the backtester. So our current risk could maybe already be 90% of equity and we can't realize it in the backtest. Most probably this is the time when people are saying that backtests are useless, but this shouldn't be our goal. So i appreciate every help !
 
Regards
 
 

function

FindValueAtDateTime( input, dt, Value )

{

found = -

1;

for( i = 0; i < BarCount AND found == - 1; i++ )

{

if( dt[ i ] == Value ) found = i;

}

return IIf( found != -1, input[ found ], Null );

}

 

if

( Status("action") == actionPortfolio )

{

AddRMultipleColumn =

StaticVarGet("AddRMultipleColumn");

bo =

GetBacktesterObject();

bo.PreProcess();

dt =

DateTime();

MaxTradeRisk =

StaticVarGet("MaxRiskPerTrade");

MaxTradeRiskPercent = MaxTradeRisk *

0.01;

Slippage =

StaticVarGet("Slippage");

UseTraceView =

StaticVarGet("UseTraceView");

UseRiskManagement =

StaticVarGet("UseRiskManagement");

 

EquityArray =

0;

CurrentContracts =

0;

EquityAtEntry =

0;

CurEquity =

0;

RiskAtCloseCash =

0;

RiskAtClosePercent =

0;

DiffToMaxRisk =

0;

RiskPerContract =

0;

ScaleAmountInContracts =

0;

ScaleAmountCashWithMargin =

0;

 

for(bar = 0; bar < BarCount; bar++)

{

bo.ProcessTradeSignals( bar );

CurEquity[bar] = bo.Equity;

if(UseRiskManagement)

{

// iterate through open trades

for( trade = bo.GetFirstopenPos(); trade; trade = bo.GetNextopenPos() )

{

// Store entry values in dynamic variables

if(trade.BarsInTrade == 1)

{

VarSet("ContractsAtEntry" + trade.Symbol, trade.Shares);

VarSet("FxRateAtEntry" + trade.Symbol, trade.EntryFxRate);

}

// Get values from entry bar

EquityAtEntry = FindValueAtDateTime( EquityArray , dt, trade.EntryDateTime );

ContractsAtEntry =

VarGet("ContractsAtEntry" + trade.Symbol);

FxRateAtEntry =

VarGet("FxRateAtEntry" + trade.Symbol);

// Store current values in dynamic variables

VarSet("CurrentContracts" + trade.Symbol, trade.Shares);

// Get current values from dynamic variables

CurrentContracts =

VarGet("CurrentContracts" + trade.Symbol);

if(bar > 0)

{

if( DiffToMaxRisk[bar-1] > 0 )

CurrentContracts = CurrentContracts - ScaleAmountInContracts[bar-

1];

else

CurrentContracts = CurrentContracts[bar-

1];

}

if(trade.IsLong)

{

// Get values from phase 1 -> composite indicators

RiskAtClose =

Foreign("~AddValues_2" + trade.Symbol, "Open");

ScalePrice = trade.GetPrice( bar,

"O" ) - Slippage ;

}

else

{

RiskAtClose =

Foreign("~AddValues_2" + trade.Symbol, "High");

ScalePrice = trade.GetPrice( bar,

"O" ) + Slippage ;

}

// Calculate current trade risk

RiskAtCloseCash[bar] = RiskAtClose[bar] * CurrentContracts[bar] * trade.PointValue * FxRateAtEntry;

RiskAtClosePercent[bar] = RiskAtCloseCash[bar] / (

0.01 * CurEquity[bar]);

DiffToMaxRisk[bar] = RiskAtCloseCash[bar] - MaxTradeRiskPercent * CurEquity[bar];

RiskPerContract[bar] = RiskAtClose[bar] * trade.PointValue * FxRateAtEntry;

ScaleAmountInContracts[bar] = DiffToMaxRisk[bar] / RiskPerContract[bar];

RoundValue =

1 / trade.RoundLotSize;

ScaleAmountInContracts[bar] =

round(ScaleAmountInContracts[bar] * RoundValue) / RoundValue;

ScaleAmountCashWithMargin[bar] = ScaleAmountInContracts[bar] * trade.MarginDeposit * FxRateAtEntry +

0.01;//0.01 necessary (rounding)

if(UseTraceView)

{

_TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", Bars In Trade = " + trade.BarsInTrade + ", Symbol " + trade.Symbol );

_TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", Contracts @ Entry = " + ContractsAtEntry + ", Current " + CurrentContracts[bar] );

// _TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", EquityAtEntry = " + EquityAtEntry + ", Current Equity = " + bo.Equity);

_TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", MaxTradeRisk = " + MaxTradeRiskPercent * bo.Equity + "€"+ ", " + MaxTradeRisk[bar] + "%" + ", DiffToMaxRisk = " + DiffToMaxRisk[bar] + " € " );

// _TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", trade.GetEntryValue() = " + trade.GetEntryValue() +" € ");

// _TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", trade.GetPositionValue() = " + trade.GetPositionValue() +" € \n\n");

// _TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", Risk = " + RiskAtClose[bar] +" Ticks, " + RiskAtCloseCash[bar] +" €, " + RiskAtClosePercent[bar] +" % ");

_TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", Current Risk = " + RiskAtCloseCash[bar] + " €, " + RiskAtClosePercent[bar] +" % ");

// _TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", FxRate @ Entry = " + FxRateAtEntry );

}

if(bar >= 0 AND DiffToMaxRisk[bar] > 0 AND UseTraceView)

_TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", Scale Out, Amount = " + DiffToMaxRisk[bar] + " €, Contracts = " + ScaleAmountInContracts[bar] );

 

if(bar > 0 AND DiffToMaxRisk[bar-1 ] > 0 )

{

bo.ScaleTrade( bar, trade.Symbol, False, ScalePrice, ScaleAmountCashWithMargin[bar-

1], trade.MarginDeposit );

if(UseTraceView)

_TRACE("bar " + bar + ", " + DateTimeToStr(dt[bar]) + ", " + ScaleAmountInContracts[bar- 1] + " Contracts scaled out ");

}

if(UseTraceView)

_TRACE("\n");

}

}

}


 
2007/7/12, Graham <kavemanperth@xxxxxxxxx>:

You would need to do the risk management within the custom backtest
coding. There is no other way to base values on portfolio equity
There are examples available (see Ab knowledge base etc) in this and a
guide written by a member of this group for advanced backtest code
available I think in the files section of yahoo group?

--
Cheers
Graham
AB-Write >< Professional AFL Writing Service
Yes, I write AFL code to your requirements
http://www.aflwriting.com



On 12/07/07, Trinolix Derry <trinolix@xxxxxxxxx> wrote:
> Hello,
>
> i have got no reply so i am wondering how you manage the trade risk ?
>
> The real risk always depends on current contracts, current equity and
> stop distance, therefore there is no easy way just as placing any
> trailing stop.
>
> Can't anyone help ?
>
>
>
> 2007/7/11, Trinolix Derry < trinolix@xxxxxxxxx>:
> > Hello,
> >
> > Can someone please tell me how to implement a simple risk management
> > for futures ?
> >
> > Compared to the AmiBroker Rebalance example which is position size
> > based, i want to use the risk amount to make rebalancing or simple
> > scale out's.
> > Basically whenever current trade risk is > 4% of current equity it
> > should scale out to get the risk below 4%.
> >
> > I wasn't able to write the code successfully, see one of my previous posts.
> > However a risk management is so important and really everyone who
> > want's to develope a serious trading system need it. So i assume that
> > anyone found the solution.
> > Otherwise Tomasz: Can you please provide a example to the KB site ?
> >
> >
> > Risk management is one of the keys to success.
> > I really appreciate every help !
> >
> > --
> > Regards
> >
>
>




--
Regards




--
Regards
__._,_.___

Please note that this group is for discussion between users only.

To get support from AmiBroker please send an e-mail directly to
SUPPORT {at} amibroker.com

For NEW RELEASE ANNOUNCEMENTS and other news always check DEVLOG:
http://www.amibroker.com/devlog/

For other support material please check also:
http://www.amibroker.com/support.html





SPONSORED LINKS
Investment management software Investment property software Investment software
Investment tracking software Return on investment software

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___