Scale in buying positions in Amibroker backtesting - trading

I have a simple backtesting code in Amibroker. It looks something like this;
Buy = BuySignal();
Sell = SellSignal();
My equity is $10000.
This code works but the limitation is that when it buys, the entire equity $10000 is sunk into the buy. What I want is something like this;
When BuySignal() is generated, buy $1000 or 10% of equity. Keep buying this amount whenever this BuySignal() is generated. If SellSignal() is generated, sell entire position.
How can I modify the code to do scaling-in of buying positions?
I am using Amibroker ver6.28.

Try this.
PosQty = 10;
SetOption("MaxOpenPositions", PosQty );
PositionSize = -100/PosQty;
Buy = IIf(BuySignal(), sigScaleIn, 0);

Related

question on coding take profit point of mt4

I have question on take profit point of mt4:
I would like to set take profit point to stop loss * 2, so the code should be:
takeprofit = NormalizeDouble((Ask + ((Ask - stoploss)*Point()*2) + StopLevel*Point()),Digits);
However, it won't works, so anyone know how to fix it? I am new to mq4 coder. Thanks
Remember that you need to differentiate between BUY and SELL orders.
You also look like you are getting confused with stoploss and StopLevel. I'm assuming that your StopLevel is the distance of your stoploss in points.
If that is the case, your code should look something like this (you don't need to reference StopLevel if you already have the distance in Points):
if(ordertype==OP_BUY) takeprofit = NormalizeDouble(Ask+StopLevel*2*Point,Digits);
else takeprofit = NormalizeDouble(Bid-StopLevel*2*Point,Digits);

What is the correct way to set StopLoss and TakeProfit in OrderSend() in MetaTrader4 EA?

I'm trying to figure out if there is a correct way to set the Stop Loss (SL) and Take Profit (TP) levels, when sending an order in an Expert Advisor, in MQL4 (Metatrader4). The functional template is:
OrderSend( symbol, cmd, volume, price, slippage, stoploss, takeprofit, comment, magic, expiration, arrow_color);
So naturally I've tried to do the following:
double dSL = Point*MM_SL;
double dTP = Point*MM_TP;
if (buy) { cmd = OP_BUY; price = Ask; SL = ND(Bid - dSL); TP = ND(Ask + dTP); }
if (sell) { cmd = OP_SELL; price = Bid; SL = ND(Ask + dSL); TP = ND(Bid - dTP); }
ticket = OrderSend(SYM, cmd, LOTS, price, SLIP, SL, TP, comment, magic, 0, Blue);
However, there are as many variations as there are scripts and EA's. So far I have come across these.
In the MQL4 Reference in the MetaEditor, the documentation say to use:
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,
NormalizeDouble(Bid - StopLoss*Point,Digits),
NormalizeDouble(Ask + TakeProfit*Point,Digits),
"My order #2",3,D'2005.10.10 12:30',Red);
While in the "same" documentation online, they use:
double stoploss = NormalizeDouble(Bid - minstoplevel*Point,Digits);
double takeprofit = NormalizeDouble(Bid + minstoplevel*Point,Digits);
int ticket=OrderSend(Symbol(),OP_BUY,1,price,3,stoploss,takeprofit,"My order",16384,0,clrGreen);
And so it goes on with various flavors, here, here and here...
Assuming we are interested in a OP_BUY and have the signs correct, we have the options for basing our SL and TP values on:
bid, bid
bid, ask
ask, ask
ask, bid
So what is the correct way to set the SL and TP for a BUY?
(What are the advantages or disadvantages of using the various variations?)
EDIT: 2018-06-12
Apart a few details, the answer is actually quite simple, although not obvious. Perhaps because MT4 only show Bid prices on the chart (by default) and not both Ask and Bid.
So because: Ask > Bid and Ask - Bid = Slippage, it doesn't matter which we choose as long as we know about the slippage. Then depending on what price you are following on the chart, you may wish to decide on using one over the other, adding or subtracting the Slippage accordingly.
So when you use the measure tool to get the Pip difference of currently shown prices, vs your "exact" SL/TP settings, you need to keep this in mind.
So to avoid having to put the Slippage in my code above, I used the following for OP_BUY: TP = ND(Bid + dTP); (and the opposite for OP_SELL.)
If you buy, you OP_BUY at Ask and close (SL, TP) at Bid.
If you sell, OP_SELL operation is made at Bid price, and closes at Ask.
Both SL and TP should stay at least within STOP_LEVEL * Point() distance from the current price to close ( Bid for buy, Ask for sell).
It is possible that STOP_LEVEL is zero - in such cases ( while MT4 accepts the order ) the Broker may reject it, based on its own algorithms ( Terms and Conditions may call it a "floating Stoplevel" rule or some similar Marketing-wise "re-dressed" term ).
It is adviced to send an OrderSend() request with zero values of SL and TP and modify it after you see that the order was sent successfully. Sometimes it is not required, sometimes that is even mandatory.
There is no difference between the two links you gave us: you may compute SL and TP and then pass them into the function or compute them based on OrderOpenPrice() +/- distance * Point().
So what is the correct way to set the SL and TP for a BUY ?
There is no such thing as "The Correct Way", there are rules to meet
Level 0: Syntax is to meet the call-signature ( the easiest one )
Level 1: all at Market XTO-s have to meet the right level of the current Price +/- slippage, make sure to repeat a RefreshRates()-test as close to the PriceDOMAIN-levels settings, otherwise they get rejected from the Broker side ( blocking one's trading engine at a non-deterministic add-on RTT-latency ) + GetLastError() == 129 | ERR_INVALID_PRICE
Level 2: yet another rules get set from Broker-side, in theire respective Service / Product definition in [ Trading Terms and Conditions ]. If one's OrderSend()-request fails to meet any one of these, again, the XTO will get rejected, having same adverse blocking effects, as noted in Level 1.
Some Brokers do not allow some XTO situations due to their T&C, so re-read such conditions with a due care. Any single of theirs rule, if violated, will lead to your XTO-instruction to get legally rejected, with all adverse effects, as noted above. Check all rules, as you will not like to see any of the following error-states + any of others, restricted by your Broker's T&C :
ERR_LONG_POSITIONS_ONLY_ALLOWED Buy orders only allowed
ERR_TRADE_TOO_MANY_ORDERS The amount of open and pending orders has reached the limit set by the broker
ERR_TRADE_HEDGE_PROHIBITED An attempt to open an order opposite to the existing one when hedging is disabled
ERR_TRADE_PROHIBITED_BY_FIFO An attempt to close an order contravening the FIFO rule
ERR_INVALID_STOPS Invalid stops
ERR_INVALID_TRADE_VOLUME Invalid trade volume
...
..
.
#ASSUME NOTHING ; Is the best & safest design-side (self)-directive

Stata daily return compounded to monthly

I have a panel datast of daily stock returns. For each stock, I need to calculate its compound monthly return (say 30 days):
(1+r_1)*(1+r_2)*...*(1+r_30) - 1
Stock identifier is permno, dm is year and month indicator. I use the following Stata code:
gen gross_ret = 1+ret
bys permno dm: gen prod = sum(ln(gross_ret))
by permno dm: replace prod = exp(prod[_N])
gen mret = prod - 1
I randomly pick permno dm combinations to verify the results, and they seem to be right. However, I do see extreme values such as mret = 26. I guess the reason is that some gross_ret is near 0, so ln(gross_ret) is very high. Then I double check using CRSP monthly return data, I found 99% of differences between compounding return (calculated by the code above) and CRSP monthly return smaller than 0.0007, which is acceptable. But the largest absolute difference is 3.24, which is too big and might affect my final result (I have been trouble shooting for two whole days, and this might be my last resort).
Is my way of calculating monthly return wrong? If so, please suggest a better way.
Perhaps you might achieve better accuracy by avoiding the logarithims, along with using double for intermediate results, as Nick recommends.
bys permno dm: gen double prod = (1+ret) if _n==1
by permno dm: replace prod = (1+ret)*prod[_n-1] if _n>1
by permno dm: gen mret = prod[_N] - 1
With that said, if you have a daily date variable (either year-month-day or just day), you could include it in the sort so your data is in the order you expect it after this process.
bys permno dm (day): gen double prod = (1+ret) if _n==1
by permno dm: replace prod = (1+ret)*prod[_n-1] if _n>1
by permno dm: gen mret = prod[_N] - 1

Keeping track of game state for a Card Trading Game

I am building a card game. Let's say it's similar to Magic the Gathering, Hearthstone, etc.
The problem I am trying to figure out is how to architect "auras" and how much damage each card takes.
Right now I have a deck and I store card data as follows. I've made up names for the types of cards that will exist.
M.card = {}
-- Minion cards have health and damage
M.card[1].name = "Minion"
M.card[1].hp = 1
M.deck[1].dmg = 1
-- Super Minions have more health and damage
M.card[2].name = "Super Minion"
M.card[2].hp = 4
M.card[2].dmg = 4
-- Spell cards have no health and damage. Instead they affect the health and damage of other cards.
M.card[3].name = "Heal"
M.card[3].details = "This card heals any character for +2 health"
M.card[3].healthboost = 2
M.card[4].name = "Damage Boost"
M.card[4].details = "This card gives + 1 damage to any other card for 1 turn"
M.card[4].dmgboost = 1
-- Super damage boost gives more damage boost to other cards
M.card[5].name = "Super Damage Boost"
M.card[5].details = "This card gives +3 damage to any other card permanently"
M.card[5].dmgboost = 3
So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments.
I could do something like this
-- Super Minion takes 3 damage
M.card[2].newHp = 1
-- or
M.card[2].adjHp = -3
-- Not sure which is better.
During the battle I need to keep track of which auras are played. So for example if the Damage boost card is played. I need to give another card +1 damage for just one turn.
Let's say that I am keep track of each turn number starting from 1.
Should I do something like this
M.aura[1] = 4 -- ( aura 1 is card # 4)
M.aura[1].target = 2 -- (this aura is applied to card 2)
M.aura[1].expires = 5 -- (this aura expires on turn 5)
M.aura[2] = 3 -- ( second active aura is heal, card #3 )
M.aura[2].target = 2
M.aura[2].expires = 0 -- this is a one time aura. So I need to apply it to card #2 and then immediately expire it so it never activates again.
Then on every new turn I loop through all the auras and make sure they are still active before a fight begins?
Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities.
Why not make the cards instances of immutable reference cards which are never altered during gameplay and compare against the parent of the instance? You could do that with some simple object orienting.
Alternatively, if that doesn't suit you, you could give each card a max or base HP field.
table.insert(M.card, {
name = "Wizard",
hp = 10,
basehp = 10,
dmg = 5
})
As for time-limited effects on cards, you could track that on the card itself.
M.card[1].effects = { { dmgboost = 2, expires = 3 } }
Give the base card a function such that it calculates the card's stats based off of effects.
function Card:damage()
local d = self.dmg
for _, v in ipairs(self.effects) do
if v.dmgboost then d = d + v.dmgboost end
end
return d
end
function Card:processEffects()
for i = #self.effects, 1, -1 do
if turn >= self.effects[i].expires then
table.remove(self.effects, i)
end
end
end
These are only a few examples out of many ways that you could handle this. However, I'm sure this will be enough to give you some ideas for now.
In order to make the existence of a card temporarily affect the qualities of another card, use an observer or callback pattern. When you "draw" (out of the deck or hand) the special card which adds +1 damage to all other friendly cards, presumably you have a function findAllOtherFriendlyCards(yourSpecialCard, allCards) which does that. Then in this function, for each friendly card you find, you "register" the friendly card with the special card by calling specialCard:registerDiscard(yourFriendlyCard). Then when the special card gets discarded, which presumably happens by calling specialCard:discard(), this method looks at all registered cards and re-adjusts the attribute that the special card affected.
In fact, you don't need a separate register method, you could just have a specialCard:startEffect(friendlyCard): this method adjusts some attributes on friendlyCard and keeps it in a list; and you have a specialCard:endEffect(friendlyCard) which does the opposite, i.e. adjusts the attributes in the opposite direction (+1 if it -1'd at start, etc) and removes the card from its list of affected cards.
If friendly cards can be discarded before the special cards get discarded, you use a similar technique: the friendly card must keep track of every special card that adjusted it and notify the special card when it gets discarded, so the special card can remove it from its list.

Computercraft variables

I am making a bank on Minecraft.
I am having trouble with saving a variable after addition or subtraction has been done to it.
For example, if x="balance", x=15, say I want to withdraw from my balance:
x = 15 - y(withdrawn money)
The variable is not saved when the program is run again.
If you want data persistence between program runs, you need to store the data in files. For example, you could save the variable x to a file like this:
h = fs.open("filename","w")
h.writeLine(x)
h.close()
And you could load it like this:
h = fs.open("filename","r")
x = tonumber(h.readLine())
h.close()
Here is the documentation. http://computercraft.info/wiki/Fs.open
Here is a first stab at it. I suppose the account balance is stored in x. Then the following function will withdraw and return money from x.
-- wa is amount to withdraw
-- this function withdraws the maximum allowable
function withdraw(wa)
if wa>0 then
wt=math.min(x,wa)
if wa <= x then
x=x-wt
return wt
end
end
return 0
end
A far more sophisticated way to keep accounts is available in the PiL book: http://www.lua.org/pil/16.html

Resources