Prevent Amibroker from entering the same day as its exit in the same symbol - amibroker

I am attempting to create a share/stock portfolio based system that will enter at the open and possibly exit on the same day at close if the conditions are met. I have this basicaly working. The thing i cant get going is that I would like my stock system to only ever have 1 open postion in a company at any time.
It seems that if there is both an exit and an entry on the same day, amibroker backtesting is allowing the same company to be purchased on the open, if that same company has a sell order on that same day. Here is an example of this:
Notice at point 1 - we would be entering at the open on the 17th
At point 2, we get a sell signal that day, so we should exit at Close on the 24th.
However at point 3 - we have an entry for the same company on the same day.
To be clear - I would like to allow multiple entries on the same day - this is working. The only thing i would like to figure out is to prevent the backtester from entering the SAME company on the SAME day it exits, as due to the system rules, we would have one day of having 2 positions in the 1 company.
Here is the sample code to replicate this:
SetOption("AllowSameBarExit", True );
SetOption("SettlementDelay", 1 );
Buy = C > MA(C,10);
Sell = C < MA(C,10) OR C > O;
// trade on todays open
SetTradeDelays( 0, 0, 0, 0 );
BuyPrice = Open;
SellPrice = Close;
SetPositionSize( 20, spsPercentOfEquity );
I have read and re-read the page on portfolio timing: here but I still cant figure out how to prevent the entries for the same company on the same day as an exit.
Any help would be greatly appreciated!
UPDATE
It appears that using the OR C > O in the SELL condition is effecting this. If I remove the OR C > O part, I get the correct behaviour. It is entering on the NEXT day. Now Im wondering how to use that exit without reverting back to same bar same company entry and exit...

Thanks to Tomasz from Amibroker for posting the below solution:
SetOption("AllowSameBarExit", True );
BuyPrice = Open;
SellPrice = Close;
Buy = Ref( Close > MA( Close, 10 ), -1 );
Sell = Close > Open OR Close < MA( Close,10);
// removing buys you don't want
intrade = False;
for( i = 0; i < BarCount; i++ )
{
if( NOT intrade )
{
if( Buy[ i ] )
{
intrade = True;
// same bar sell
if( Sell[ i ] ) intrade = False;
}
}
else
{
if( Sell[ i ] )
{
intrade = False;
Buy[ i ] = False; // remove buy if exited this bar
}
}
}
You can find : a detailed discussion here

Related

AHK loop High CPU Usage

I'm running an Autohotkey script that auto capitalizes the first character of a sentence (for example in Texstudio or Chrome). The script (specifically the loop I guess) sometime causes 30–40% of CPU. Therefore, I am wondering if there is a possibility to optimize the code (maybe without using loop?) to reduce the CPU usage. Thanks in advance. Here is the code:
#SingleInstance force
#NoEnv
SetBatchLines -1
Loop {
if WinActive("ahk_exe texstudio.exe") or WinActive("ahk_exe chrome.exe")
Input key, I L1 M V,{Esc}{BS}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Tab}
StringUpper key, key
If InStr(ErrorLevel,"EndKey")
state =
Else If InStr(".!?",key)
state = 1
Else If InStr("`t `n",key) {
If state = 1
state = 2
} Else {
If state = 2
Send {BS}{%key%}
state =
}
}
Return
SetTimer consumes much less CPU because of the period.
#SingleInstance force
#NoEnv
#Persistent
; SetBatchLines -1
; create a group of the programs in which you want auto-capitalize
GroupAdd, auto_capitalize_group, ahk_exe texstudio.exe
GroupAdd, auto_capitalize_group, ahk_exe chrome.exe
SetTimer, auto_capitalize, 300 ; check every 300 ms
Return
auto_capitalize:
if !WinActive("ahk_group auto_capitalize_group")
return ; do nothing
; otherwise:
Input key, I L1 M V,{Esc}{BS}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Tab}
StringUpper key, key
If InStr(ErrorLevel,"EndKey")
state =
Else If InStr(".!?",key)
state = 1
Else If InStr("`t `n",key)
{
If state = 1
state = 2
}
Else
{
If state = 2
Send {BS}{%key%}
state =
}
Return

Is there a way in Amibroker backtest to specify buy price?

Is there a way to place buy order at a certain value?
I am trying to buy at the break of previous day high on a 5 min tf:
DayH = TimeFrameGetPrice("H", inDaily, -1); // yesterdays high
DayL = TimeFrameGetPrice("L", inDaily, -1); // low
DayC = TimeFrameGetPrice("C", inDaily, -1); // close
DayO = TimeFrameGetPrice("O", inDaily); // current day open
Buy = H >= DayH AND DayO < DayH;
BuyPrice = DayH;
But I am not able to get the buy price similar to yesterday's high, its always something more or less
Use SetTradeDelays()
Buy = High
SetTradeDelays(-1,-1,-1,-1);

Simple highscore using preferences (Lua - Corona SDK)

And thanks in advance for your help!
I'm trying to implement in my game an highscore feature using "preferences" in Lua, but i'm missing something, here's my code:
local highscore_letta = system.getPreference( "app", "highscore", "number" )
-- if preference do not exist, create it and set it to 0 (first time playing the game)
if (highscore_letta == nil) then
local appPreferences =
{
highscore = "0"
}
system.setPreferences( "app", appPreferences )
end
-- if the score is higher than current highscore, update it with the new one
if (_G.player_score > highscore_letta) then
local appPreferences =
{
highscore = _G.player_score
}
system.setPreferences( "app", appPreferences )
end
After the player lose for the first time, the game crashes saying that it's comparing a null value in "highscore_letta".
After a second try, the game do not crashes, but it sticks with 0 and never update it at all.
Any advice? I can't figure out what i'm missing.
Thanks again!
Try
local highscore_letta = system.getPreference( "app", "highscore", "number" ) or 0
-- if the score is higher than current highscore, update it with the new one
if (_G.player_score > highscore_letta) then
local appPreferences =
{
highscore = _G.player_score
}
system.setPreferences( "app", appPreferences )
end

AHK IF statement

ArrayCount = 0
Loop, Read, Times.txt ; This loop retrieves each line from the file.
{
ArrayCount += 1 ; Keep track of how many items are in the array.
ArrayTime%ArrayCount% := A_LoopReadLine
}
WinGetTitle, Title, A
Loop %ArrayCount%
{
element := ArrayTime%A_Index%
Time = %A_WDay%%A_Hour%%A_Min%
msgbox %Time% , %element%
if (Time=%element%)
{
IfWinExist, Test.txt
{
WinActivate
Sleep 500
Send Hi{enter}
msgbox %Time% , %element%
Sleep 500
WinActivate, %Title%
}
}
}
Ok so the main issue is with this part:
if (Time=%element%)
I have also tried
if (%Time%=%element%)
if (A_WDay . A_Hour . A_Min=%element%)
And I think some other similar variations, the problem I'm getting is it's either always true, or always false, depending on how I have it written.
Inside the text file is a list like this:
10000
10700
11400
20400
21100
I add an extra line that has the current time for testing, and I added the msgbox to compare, and I can clearly see they're both the same when it doesn't work, or that they're different when it does. Sorry for such a basic question but I feel like I've really been trying for a long time and read everything I can on variables and IF statements, thanks for any help.
Also the point of it is I need it to go off every 7 hours starting at midnight on sunday, this is what I came up with, if there's maybe a completely better way in general I'd be happy to hear that too.
Try this:
if % Time = element
{
MsgBox, Equal!
}
As for the scheduling part, try running your script through Windows Task Scheduler (hit Windows+R, type taskschd.msc and press Enter). There are tutorials on the Internet explaining how to create new tasks.
With regard to timers, have a look at this as an example.
SetTimer, AlertType1, 60000
ToAlertType1:=1
ToAlertType2:=1
AlertType1:
;If A_WDay between 2 and 7 ; is day monday - sunday?
;{
If (A_Hour = 7 or A_Hour = 13)
{
If (ToAlertType1)
{
SoundBeep, 500, 500
ToAlertType2:=1
ToAlertType1:=0
MsgBox, 4096,%AppName%, Msg1.
Return
}
}
Else if (A_Hour = 21)
{
If (ToAlertType2)
{
SoundBeep, 500, 500
ToAlertType2:=0
ToAlertType1:=1
MsgBox, 4096,%AppName%, Msg2.
Return
}
}
;}
Return

How to do a "while quantity is greater than zero loop"

So I am using a gift certificate module with satchmo store and in order to send multiple gift certificate codes equal to the number of items purchased I need to add a loop doing
"while quantity is greater than zero loop"
Here is the code, the loop is being added to right before "price=order_item.unit_price"
def order_success(self, order,
order_item):
log.debug("Order success called, creating gift certs on order:
%s", order)
message = ""
email = ""
for detl in order_item.orderitemdetail_set.all():
if detl.name == "email":
email = detl.value
elif detl.name == "message":
message = detl.value
price=order_item.unit_price
log.debug("Creating gc for %s", price)
gc = GiftCertificate(
order = order,
start_balance= price,
purchased_by = order.contact,
valid=True,
message=message,
recipient_email=email
)
gc.save()
I am not sure I understand the question, but maybe something like
for ix in range(0, order_item.quantity):
... do stuff
might do the trick. You don't have to use the ix anywhere inside the loop, it is just (arguably) the standard way to do something n times in Python.

Resources