From e9eb2c8eb77e4bb02e221581078f582b2403d2c4 Mon Sep 17 00:00:00 2001 From: Rose Heart Date: Fri, 27 Sep 2024 17:09:02 +0000 Subject: [PATCH] Bug fixes. Visual improvements in OliverTwist charting. Changes to be committed: modified: Base/Library/OliverTwist-oanda.py modified: Extras/OliverTwist/OliverTwistEquity modified: Extras/OliverTwist/OliverTwistTrades --- Base/Library/OliverTwist-oanda.py | 21 +++++++++---- Extras/OliverTwist/OliverTwistEquity | 6 ++-- Extras/OliverTwist/OliverTwistTrades | 44 ++++++++++++++++++---------- 3 files changed, 47 insertions(+), 24 deletions(-) diff --git a/Base/Library/OliverTwist-oanda.py b/Base/Library/OliverTwist-oanda.py index c131986..1c86a98 100755 --- a/Base/Library/OliverTwist-oanda.py +++ b/Base/Library/OliverTwist-oanda.py @@ -220,7 +220,7 @@ 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'] @@ -228,11 +228,15 @@ def ReduceLotSize(relay,oldestTrade=None,val=1): # 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. @@ -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'] @@ -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)}") diff --git a/Extras/OliverTwist/OliverTwistEquity b/Extras/OliverTwist/OliverTwistEquity index 45f62bf..723b239 100755 --- a/Extras/OliverTwist/OliverTwistEquity +++ b/Extras/OliverTwist/OliverTwistEquity @@ -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(' ') @@ -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) diff --git a/Extras/OliverTwist/OliverTwistTrades b/Extras/OliverTwist/OliverTwistTrades index 1fe86e3..ca7bffd 100755 --- a/Extras/OliverTwist/OliverTwistTrades +++ b/Extras/OliverTwist/OliverTwistTrades @@ -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 @@ -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 @@ -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 @@ -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) @@ -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: @@ -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())) @@ -202,14 +202,23 @@ 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 cdt0: # 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)