Skip to content

Commit

Permalink
Bug fixes.
Browse files Browse the repository at this point in the history
Visual improvements in OliverTwist charting.

Changes to be committed:
	modified:   Base/Library/OliverTwist-oanda.py
	modified:   Extras/OliverTwist/OliverTwistEquity
	modified:   Extras/OliverTwist/OliverTwistTrades
  • Loading branch information
rapmd73 committed Sep 27, 2024
1 parent e098105 commit e9eb2c8
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 24 deletions.
21 changes: 15 additions & 6 deletions Base/Library/OliverTwist-oanda.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,19 +220,23 @@ def CalculatePriceExit(order,ts,dir,price,onePip):

def ReduceLotSize(relay,oldestTrade=None,val=1):
try:
relay.JRLog.Write(f"RLS A: {json.dumps(oldestTrade)}")
# relay.JRLog.Write(f"RLS A: {json.dumps(oldestTrade)}")
if oldestTrade==None:
return
Order=oldestTrade['Order']
pair=Order['Asset']

# Verify the trade exists. If it doesn't, delete the key
if not TradeExists(relay,oldestTrade['ID'],pair):
relay.JRLog.Write("RLS B",oldestTrade)
# relay.JRLog.Write("RLS B",oldestTrade)
return

lossID=oldestTrade['ID']
lossIU=float(oldestTrade['Response']['units'])
parts=oldestTrade['Response']['time'].split('.')
dsS=f"{parts[0]}.{parts[1][:6]}Z"
ds=datetime.datetime.strptime(dsS,'%Y-%m-%dT%H:%M:%S.%fZ')
price=float(oldestTrade['Price'])

# Get the direction of the reduction trade right.

Expand All @@ -245,7 +249,7 @@ def ReduceLotSize(relay,oldestTrade=None,val=1):
Dir='long'
Action='Sell'

relay.JRLog.Write("RLS C")
# relay.JRLog.Write("RLS C")
newOrder={}
newOrder['OliverTwist']='Conditional ReduceBy'
newOrder['Exchange']=Order['Exchange']
Expand All @@ -262,17 +266,22 @@ def ReduceLotSize(relay,oldestTrade=None,val=1):
newOrder['OrderType']='market'
newOrder['Identity']=relay.Active['Identity']

relay.JRLog.Write("RLS D")
# relay.JRLog.Write("RLS D")
# Feed the new order to Relay
result=relay.SendWebhook(newOrder)
oid=relay.GetOrderID(result)
relay.JRLog.Write(f"RLS E: {result}")
# relay.JRLog.Write(f"RLS E: {result}")
if oid!=None:
orderDetail=relay.GetOrderDetails(OrderID=oid)
# find trade close time and duration
parts=orderDetail[-1]['time'].split('.')
deS=f"{parts[0]}.{parts[1][:6]}Z"
de=datetime.datetime.strptime(deS,'%Y-%m-%dT%H:%M:%S.%fZ')
duration=de-ds

sprice=float(orderDetail[-1]['price'])
rpl=float(orderDetail[-1]['pl'])
relay.JRLog.Write(f"{lossID} -> {oid} Rduc {Dir}, {val}: {price:.5f} -> {sprice:5f}/{rpl:.5f}")
relay.JRLog.Write(f"{lossID} -> {oid} Rduc {Dir}, {val}: {price:.5f} -> {sprice:5f}/{abs(rpl):.5f}, {duration}")
except Exception as e:
# Something broke or went horrible wrong
relay.JRLog.Write(f"ReduceLotSize: {sys.exc_info()[-1].tb_lineno}/{str(e)}")
Expand Down
6 changes: 4 additions & 2 deletions Extras/OliverTwist/OliverTwistEquity
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ for line in lines:
line=line.lower()
if line=='' or ('prft' not in line and 'loss' not in line and 'rduc' not in line):
continue
if 'broke' in line:
continue

data=line.split(' ')

Expand All @@ -69,9 +71,9 @@ for line in lines:
pdata=line.split('/')[1].strip().split(',')[0]

if 'prft' in line.lower():
pnl+=float(pdata)
pnl+=abs(float(pdata))
if 'loss' in line or 'rduc' in line:
pnl-=float(pdata)
pnl-=abs(float(pdata))

xps.append(dt)
equity.append(pnl)
Expand Down
44 changes: 28 additions & 16 deletions Extras/OliverTwist/OliverTwistTrades
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ interceptor=JRRsupport.SignalInterceptor(Log=Log)

DataDirectory='/home/JackrabbitRelay2/Data'
chartDir=DataDirectory+'/Charts/'
Storehouse=DataDirectory+'/OliverTwist.Storehouse'
OliverTwistData=DataDirectory+'/OliverTwist'

# For reading the storehouse

Expand All @@ -38,6 +38,7 @@ OliverTwistLock=JRRsupport.Locker("OliverTwist")
def ReadStorehouse(exchange,account,asset):
global OliverTwistLock

Storehouse=f"{OliverTwistData}/{exchange}.{account}.{asset}.Storehouse"
OrphanList=[]

WorkingStorehouse=Storehouse
Expand Down Expand Up @@ -74,8 +75,7 @@ def ReadStorehouse(exchange,account,asset):
detail.pop('Identity',None)
Orphan['Detail']=detail

if Orphan['Order']['Exchange']==exchange and Orphan['Order']['Account']==account and Orphan['Order']['Asset']==asset:
OrphanList.append(Orphan)
OrphanList.append(Orphan)

OliverTwistLock.Unlock()
return OrphanList
Expand All @@ -90,7 +90,7 @@ def FindStartDateTime(end_date_str, duration_str):
time_parts = duration_parts[1].split(':')
hours = int(time_parts[0])
minutes = int(time_parts[1])
seconds = float(time_parts[2])
seconds = float(time_parts[2].replace(',',''))

# Calculate start date
start_date = end_date - datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
Expand Down Expand Up @@ -132,7 +132,7 @@ for i in range(1,len(sys.argv)):
print("Phase 1: read log file")
data=gblog.split('.')

exchange=data[1].lower()
exchange=data[1]
account=data[2]

if len(data)==5:
Expand All @@ -144,7 +144,7 @@ else:

# For Mimic, use the Details section to get the Price

OpenOrders=ReadStorehouse(exchange,account,pair)
OpenOrders=ReadStorehouse(exchange,account,asset)
if OpenOrders!=[]:
OpenOrderDT=datetime.datetime.strptime(OpenOrders[0]['DateTime'], '%Y-%m-%d %H:%M:%S.%f')
OpenEpoch=int(time.mktime(OpenOrderDT.timetuple()))
Expand Down Expand Up @@ -202,22 +202,31 @@ fig1=ps.make_subplots(specs=[[{"secondary_y":False}]])

print("Phase 2: making the chart")

# Plot candles of timeframe just above log
# Get the first candle of the trades to set the start of the chart.
fid=lines[0].split(' ')[4]
oDetails=relay.GetOrderDetails(OrderID=fid)[0]
print(oDetails['time'])
sdt=datetime.datetime.strptime(oDetails['time'].split('T')[0], '%Y-%m-%d').timestamp()

# Plot candles of timeframe just above log
dt=[]
do=[]
dh=[]
dl=[]
dc=[]
for slice in ohlcv:
cdt=slice[0]/1000
# Do not add candles before forst trade
if cdt<sdt:
continue
dt.append(datetime.datetime.fromtimestamp(slice[0]/1000))
do.append(slice[1])
dh.append(slice[2])
dl.append(slice[3])
dc.append(slice[4])
fig1.add_trace(go.Candlestick(x=dt,open=do,high=dh,low=dl,close=dc,increasing_line_color='#a0ffff',decreasing_line_color= '#ffa0ff'),secondary_y=False)

# Process open opders for oanda
# Process open orders for oanda

dt=[]
dp=[]
Expand All @@ -242,7 +251,10 @@ for order in OpenOrders:
# Plot trades

for line in lines:
if line=='' or ('Prft' not in line and 'Loss' not in line and 'Rduc' not in line):
line=line.lower()
if line=='' or ('prft' not in line and 'loss' not in line and 'rduc' not in line):
continue
if 'broke' in line:
continue

data=line.split(' ')
Expand All @@ -255,12 +267,12 @@ for line in lines:
dur=f"{data[12]} {data[13]} {data[14]}"
else:
dur=f"0 days, {data[12]}"
bTime=FindStartDateTime(dt,dur)

# Prft/Loss
action=data[6]
dir=data[7].split(',')[0].lower()
dir=data[7].split(',')[0]

bTime=FindStartDateTime(dt,dur)
amount=abs(float(data[8].split(':')[0]))
bPrice=float(data[9])

Expand All @@ -274,15 +286,15 @@ for line in lines:
else:
rpl=(bPrice-sPrice)*amount

if action.lower()=='prft' and rpl>0: # Profit
if action=='prft' and rpl>0: # Profit
col="rgba(0,128,0,1)"
elif action.lower()=='prft' and rpl==0: # Breakeven
elif action=='prft' and rpl==0: # Breakeven
col="rgba(128,128,0,1)"
elif action.lower()=='prft' and rpl<0: # Loss by slippage
elif action=='prft' and rpl<0: # Loss by slippage
col="rgba(255,128,0,0.5)"
elif action.lower()=='rduc': # ReduceBy
elif action=='rduc': # ReduceBy
col="rgba(0,255,255,0.01)"
elif action.lower()=='loss': # Stoploss
elif action=='loss': # Stoploss
col="rgba(128,0,0,0.5)"
else:
print('L:',line)
Expand Down

0 comments on commit e9eb2c8

Please sign in to comment.