Skip to content

Commit

Permalink
Bug fixes.
Browse files Browse the repository at this point in the history
Version update.

Changes to be committed:
	modified:   Base/Conditional.mimic
	modified:   Base/Library/JRRmimic.py
	modified:   Base/MIMIC-PlaceOrder
	modified:   Extras/otcWatch
  • Loading branch information
rapmd73 committed Mar 1, 2024
1 parent 788fcef commit 342457f
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 94 deletions.
5 changes: 1 addition & 4 deletions Base/Conditional.mimic
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,7 @@ def main():
# Check to see if we have enough balance, if not then delete this order. Deal with futures as well.

base=relay.Markets[relay.Order['Asset']]['base'].upper()
if relay.Order['Market']=='spot':
bal=relay.GetBalance(Base=base)
else:
bal=relay.GetPositions(symbols=[relay.Order['Asset']])
bal=relay.GetBalance(Base=base)

# if ticker is below price and spread, purge and re-purchase

Expand Down
42 changes: 26 additions & 16 deletions Base/Library/JRRmimic.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def GetOpenTrades(self,**kwargs):
def UpdateWallet(self,action,asset,amount,price,fee_rate=0):
# if the account has already been disabled (liquidated), then don't waste time here
if self.Wallet['Enabled']=='N':
return '{ "Error":"Account Liquidated!" }'
return 'Account Disabled From Liquidated!'

# action is assumed to be only lowercase at this point.
# Split the asset pair into base and quote currencies
Expand Down Expand Up @@ -273,12 +273,10 @@ def UpdateWallet(self,action,asset,amount,price,fee_rate=0):
if quote in self.Wallet['Wallet'] and self.Wallet['Wallet'][quote] >= total_cost:
# Deduct the total cost including fees from the quote currency balance
self.Wallet['Wallet'][quote]-=total_cost
# Add the appropriate amount of the base currency to the base currency wallet
# Add the appropriate amount of the base currency to the base currency wallet.
# Using negatives as shorts allows position flipping by default.
if base in self.Wallet['Wallet']:
if actualAmount<0:
self.Wallet['Wallet'][base]-=actualAmount
else:
self.Wallet['Wallet'][base]+=actualAmount
self.Wallet['Wallet'][base]+=actualAmount
else:
self.Wallet['Wallet'][base]=actualAmount # Initialize the base currency wallet if not present
# Update fee balance
Expand All @@ -305,7 +303,7 @@ def UpdateWallet(self,action,asset,amount,price,fee_rate=0):
else:
# Not enough balance, account liquidated.
self.Wallet['Enabled']='N'
return '{ "Error":"Account Liquidated!" }'
return 'Account Liquidated!'
elif action=='sell':
# Check if the base currency is present in the base currency wallet and the amount to sell is available
if base in self.Wallet['Wallet'] and self.Wallet['Wallet'][base] >= abs(actualAmount):
Expand All @@ -326,7 +324,7 @@ def UpdateWallet(self,action,asset,amount,price,fee_rate=0):
if 'Fees' in self.Wallet['Wallet']:
self.Wallet['Wallet']['Fees']+=fee
else:
self.Wallet['Wallet']['Fees'] = fee # Initialize fee balance if not present
self.Wallet['Wallet']['Fees']=fee # Initialize fee balance if not present
# Update successful
order={}
order['DateTime']=(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
Expand All @@ -345,9 +343,9 @@ def UpdateWallet(self,action,asset,amount,price,fee_rate=0):
else:
# Not enough balance, but account is not liquidated. Need to cross analyze this on shorting.
#self.Wallet['Enabled']='N'
return '{ "Error":"Not enough balance!" }'
return 'Not enough balance!'
else: # Should NEVER happen.
return '{ "Error":"Invalid action!" }'
return 'Invalid action!'

# Welcome to the nightmare: placing and maintaining orders.

Expand All @@ -374,10 +372,14 @@ def PlaceOrder(self,**kwargs):
m=kwargs.get('orderType').lower()
action=kwargs.get('action').lower()
price=kwargs.get('price')
# ln=kwargs.get('LedgerNote')
ln=kwargs.get('LedgerNote',None)
# Shorts are stored as negative numbers
amount=float(kwargs.get('amount'))
Quiet=kwargs.get('Quiet')
ro=kwargs.get('ReduceOnly',False)
Quiet=kwargs.get('Quiet',False)

# Split the asset pair into base and quote currencies
base,quote=pair.split('/')

# simulate a real order
order={}
Expand All @@ -400,6 +402,10 @@ def PlaceOrder(self,**kwargs):
else:
Fee=self.DefaultFeeRate

# Handle ReduceOnly
if ro==True and action=='sell':
amount=self.Wallet['Wallet'][base]

result=self.UpdateWallet(action,pair,amount,price,Fee)
JRRsupport.AppendFile(self.history,json.dumps(result)+'\n')
self.PutWallet()
Expand All @@ -414,20 +420,24 @@ def PlaceOrder(self,**kwargs):
#JRRledger.WriteLedger(pair, m, action, amount, price, order, ln)
return order
else: # We have an error
return result
self.Log.Error("PlaceOrder",result)

# Get the details of the completed order. This will reaD from the positions list.

def GetOrderDetails(self,**kwargs):
if os.path.exists(self.history):
id=kwargs.get('id')
id=kwargs.get('ID')
pair=kwargs.get('pair',None)
cf=open(self.history,'r')
# We need to go line by line as history file may be too large to load
for line in cf.readlines():
if line=='':
line=line.strip()
if line=='' or (line[0]!='{' and line[-1]!='}'):
continue
try: # skip non-JSON lines
order=json.loads(line)
except:
continue
order=json.loads(line)
if (order['ID']==id and pair!=None and order['Asset']==pair) \
or (order['ID']==id and pair==None):
cf.close()
Expand Down
2 changes: 1 addition & 1 deletion Base/MIMIC-PlaceOrder
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def main():
elif relay.Order['Action']=='short':
relay.Order['Action']='sell'

if amount>0:
if abs(amount)!=0:
lNote=None
if 'LedgerNote' in relay.Order:
lNote=relay.Order['LedgerNote']
Expand Down
12 changes: 10 additions & 2 deletions Extras/otcWatch
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ def main():
price=float(Detail['Price'])
amount=float(Detail['Amount'])

# find trading duration
parts=Detail['DateTime'].split('.')
dsS=f"{parts[0]}.{parts[1][:6]}Z"
ds=datetime.datetime.strptime(dsS,'%Y-%m-%d %H:%M:%S.%fZ')
deS=datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
de=datetime.datetime.strptime(deS,'%Y-%m-%d %H:%M:%S.%f')
duration=de-ds

if amount>=0:
dir='long'
tprice=ticker['Bid']
Expand All @@ -166,7 +174,7 @@ def main():

tp=round(CalculatePriceExit(Order,'TakeProfit',dir,price),8)
sl=round(CalculatePriceExit(Order,'StopLoss',dir,price),8)
print(f"{id} {Order['Asset']:14} {sl:.8f} {tprice:.8f}({price:.8f}) {tp:.8f} {amount:.8f} {dir}")
print(f"{id} {Order['Asset']:14} {sl:.8f} {tprice:.8f}({price:.8f}) {tp:.8f} {amount:.8f} {dir} {duration}")
elif Data['Framework']=='oanda':
Resp=Data['Response']
id=Data['ID']
Expand Down Expand Up @@ -218,7 +226,7 @@ def main():
slPips=""
if sl!=0:
slPips=f"({Order['StopLoss']})"
print(f"{id:10} {Order['Asset']:10} {sl:.5f} {slPips:<10} {tprice:.5f}({price:.5f}) {tp:.5f} {tpPips:<10} {rpl:.5f} {abs(amount):4.0f} {dir}, {duration}")
print(f"{id:10} {Order['Asset']:10} {sl:.5f} {slPips:<10} {tprice:.5f}({price:.5f}) {tp:.5f} {tpPips:<10} {rpl:.5f} {abs(amount):4.0f} {dir} {duration}")
else:
print("No conditional orders yet.")
sys.exit(0)
Expand Down
71 changes: 0 additions & 71 deletions WalletTest.py

This file was deleted.

6 changes: 6 additions & 0 deletions x1
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# find trade close time and duration
parts=orderDetail[0]['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

0 comments on commit 342457f

Please sign in to comment.