

# This file is generated by pto-pre-build.sh. Do not edit it manually.







# DONT EDIT THIS FILE MANUALLY. IT IS GENERATED BY pto-pre-build.sh








#DONT EDIT THIS FILE MANUALLY. IT IS GENERATED BY pto-pre-build.sh






# Mon 19 Aug 2024 03:54:47 AM EDT
# SOURCE NAME: /b/Dropbox/jgt/drop/fnml.py
########################
 

import argparse
import os
import subprocess

from jgtcliconstants import (CLI_FXADDORDER_PROG_NAME,CLI_FXMVSTOP_PROG_NAME,CLI_FXRMORDER_PROG_NAME,CLI_FXRMTRADE_PROG_NAME,CLI_FXTR_PROG_NAME,PDSCLI_PROG_NAME)

from jgtconstants import (LIPS,TEETH,JAW)
from jgtconstants import FDB,HIGH,LOW,CLOSE

from jgtpyconstants import (IDSCLI_PROG_NAME,CDSCLI_PROG_NAME,ADSCLI_PROG_NAME,MKSCLI_PROG_NAME,JGTCLI_PROG_NAME)

try:
  from mlcliconstants import (MLFCLI_PROG_NAME,TTFCLI_PROG_NAME,PNCLI_PROG_NAME,MXCLI_PROG_NAME)
except:
  from mlcliconstants import (MLFCLI_PROG_NAME,TTFCLI_PROG_NAME,PNCLI_PROG_NAME,MXCLI_PROG_NAME) # type: ignore


def fxaddorder( instrument, lots, rate, buysell, stop, demo=False,flag_pips=False):
  pips_arg = '--pips' if flag_pips else ''
  demo_arg = '--demo' if demo else '--real'
  subprocess.run([CLI_FXADDORDER_PROG_NAME, '-i', instrument, '-n', lots, '-r', rate, '-d', buysell, '-x',stop,pips_arg , demo_arg])

def fxrmorder(orderid, demo=False):
  demo_arg = '--demo' if demo else '--real'
  subprocess.run([CLI_FXRMORDER_PROG_NAME, '-id', orderid, demo_arg])

def fxrmtrade(tradeid, demo=False):
  demo_arg = '--demo' if demo else '--real'
  subprocess.run([CLI_FXRMTRADE_PROG_NAME, '-tid', tradeid, demo_arg])

def fxtr(tradeid=None,orderid=None, demo=False,save_flag=True):
  save_arg = '-save' if save_flag else ''
  demo_arg = '--demo' if demo else '--real'
  if tradeid:
    subprocess.run([CLI_FXTR_PROG_NAME, '-tid', tradeid, demo_arg, save_arg])
  elif orderid:
    subprocess.run([CLI_FXTR_PROG_NAME, '-id', orderid, demo_arg, save_arg])
  else:
    subprocess.run([CLI_FXTR_PROG_NAME, demo_arg, save_arg])
  print("Should have two files created for the treansaction")

def fxmvstop(tradeid,stop,flag_pips=False, demo=False):
  pips_arg = '--pips' if flag_pips else ''
  demo_arg = '--demo' if demo else '--real'
  cli_args = [CLI_FXMVSTOP_PROG_NAME, '-tid', tradeid, '-x', stop, demo_arg]
  if pips_arg != '':
    cli_args.append(pips_arg)
  subprocess.run(cli_args)

def ids(instrument, timeframe,use_full=False,use_fresh=True):
  use_fresh_arg = '-old' if not use_fresh else '--fresh'
  use_full_arg = '--full' if use_full else '-new'
  subprocess.run([IDSCLI_PROG_NAME, '-i', instrument, '-t', timeframe, use_full_arg, use_fresh_arg])

"""
fxmvstopgator -tid 68773276  --demo -i AUD/NZD -t H4 --lips
"""
#@STCGoal RM Order if Stop was Hit


#from jgtpy.jgtapyhelper import select_value_in_currentbar,select_value_in_lastcompletedbar
import jgtapyhelper as th


#@STCGoal Move EXIT Stop On FDB Signal
fxmvstopfdb_epilog = "Move the stop to the FDB signal. If the stop is already hit, close the trade if --close is passed.  Considering we could add --lips to move the stop to the lips if no FDB signal is found #@STCIssue It would requires to detect if previously the stop was moved to an FDB signal (as we dont want to move it again back in the lips if we are still in an FDB signal)"

def fxmvstopfdb(i,t,tradeid,demo=False,close=False):
  demo_arg="--demo" if demo else "--real"
  if close:
    print("Closing the trade if the stop of fdbsignal is already hit")
    raise NotImplementedError("Closing the trade if the stop of fdbsignal is already hit")
  
  
  
  
  #Update the local datafor the trade
  ## we expect : fxtransact_68782480.json
  #fxtr(tradeid=tradeid,demo=demo)
  expected_fn=f"fxtransact_{tradeid}.json"
  from FXTransact import FXTransactWrapper,FXTransactDataHelper as ftdh,FXTrades,FXTrade
  print("reading the trade data from the file:",expected_fn)
  fxdata=ftdh.load_fxtransact_from_file(expected_fn)
  trade_data:FXTrade=None
  trades:FXTrades=fxdata.trades
  for trade in trades.trades:
    #print(trade)
    if str(trade["trade_id"])==str(tradeid):
      trade_data=trade
      break

  #fuck=fxtrades[tradeid]
  #get the trade data
  #print(fxdata)
  #trade_data=ftdh.load_fxtrade_from_fxtransact(fxdata,tradeid)
  #trade_data2=fxdata.get_trade(tradeid)
  direction=trade_data["buy_sell"]
  original_stop=trade_data["stop"]
  print("Direction, so we know which col of the bars to look for.",direction)
  print(trade_data)
  #@STCIssue Why do I want that info on the Trade ??
  
    
  skip_generating_ids=False
  #if SKIP_IDS defined in os env, skip
  if os.getenv("SKIP_IDS"):
    skip_generating_ids=True
    
  if skip_generating_ids:
    print("Skipping generating IDS (JUST READING  IT FOR DEV)")
  
  df = _get_ids_updated(i, t,skip_generating=skip_generating_ids)
  from JGTIDS import _ids_add_fdb_column_logics_v2
  dfc=_ids_add_fdb_column_logics_v2(df)
  lcb=dfc.iloc[-2]
  lcbfdb = lcb[FDB]
  lcbhigh=lcb[HIGH]
  lcblow=lcb[LOW]
  cb=dfc.iloc[-1]
  clow=cb[LOW]
  cclose=cb[CLOSE]
  chigh=cb[HIGH]
  
  is_sell_fdb=lcbfdb<0
  is_buy_fdb=lcbfdb>0
  stop_price=None
  if direction=="B" and is_sell_fdb:
    stop_price=lcblow
  else:
    if direction=="S" and is_buy_fdb:
      stop_price=lcbhigh
      
  
  if stop_price:
    msg_ = f"We change the Stop for:{stop_price} from : {original_stop}"
    print(msg_)
    #@q Does our Current Bar Broke the FDB Signal ??
    #@STCIssue If close is True, we should close the trade if the stop is already hit
    stop_has_hit=False
    if direction=="B" and cclose>stop_price:
      stop_has_hit=True
    else: 
      if direction=="S" and cclose<stop_price:
        stop_has_hit=True
    msg=f"Stop has hit" if stop_has_hit else "Stop has not hit"
    print(msg)
      
  else:
    print("We dont have a signal, Shall we fall in set the stop to the lips ??")
    fxmvstopgator_cmd = f"jgtapp fxmvstopgator -i {i} -t {t} -tid {tradeid} --lips {demo_arg}"
    print(fxmvstopgator_cmd)
  
  
  
  

def _get_ids_updated(i, t,skip_generating=False):
    try:
      if not skip_generating:
        ids(i,t,use_fresh=True,use_full=False)
    except:
      print("IDS failed")
  #read the last bar from the IDS csv
    df=th.read_ids(i,t)
    return df
    
  
  

def fxmvstopgator(i,t,tradeid,lips=True,teeth=False,jaw=False,demo=False):
  

    
  #First update the IDS
  df = _get_ids_updated(i, t)
  #get the last bar
  last_bar=df.iloc[-1]
  choosen_line="_"
  #get the stop from choosen indicator line (by flag)
  if not teeth and not jaw:
    lips=True # DEFAULT
  if lips:
    stop=str(last_bar[LIPS])
    choosen_line="lips"
  elif teeth:
    stop=str(last_bar[TEETH])
    choosen_line="teeth"
  elif jaw:
    stop=str(last_bar[JAW])
    choosen_line="jaw"
  else:
    raise ValueError("No indicator line selected")
  print(f"Stop made of choosen line ({choosen_line}):: ",stop)
  #Then move the stop
  fxmvstop(tradeid,stop,demo=demo)

def tide(instrument, timeframe, buysell):
  raise DeprecationWarning("tide is deprecated. ")
  #subprocess.run(['tide', instrument, timeframe, buysell])

def pds(instrument, timeframe,use_full=True):
  use_full_arg = '--full' if use_full else ''
  subprocess.run([PDSCLI_PROG_NAME, '-i', instrument, '-t', timeframe, use_full_arg])

def cds(instrument, timeframe, use_fresh=False,use_full=True):
  use_full_arg = '--full' if use_full else ''
  old_or_fresh = '-old' if not use_fresh else '--fresh'
  subprocess.run([CDSCLI_PROG_NAME, '-i', instrument, '-t', timeframe,use_full_arg, old_or_fresh])

def ocds(instrument, timeframe,use_full=True):
  use_full_arg = '--full' if use_full else ''
  subprocess.run([JGTCLI_PROG_NAME, '-i', instrument, '-t', timeframe, use_full_arg, '-old'])

  
def ttf(instrument, timeframe,pn="ttf",use_fresh=False,use_full=True):
  use_full_arg = '--full' if use_full else ''
  use_fresh_arg = '-old' if not use_fresh else '--fresh'
  
  ttf_args = [TTFCLI_PROG_NAME, '-i', instrument, '-t', timeframe, use_full_arg, use_fresh_arg, '-pn', pn]
  print("TTF is being ran by jgtapp with args: ", ttf_args)
  subprocess.run(ttf_args)


def mlf(instrument, timeframe,pn="ttf",total_lagging_periods=5,use_fresh=False,use_full=True):
  use_full_arg = '--full' if use_full else ''
  use_fresh_arg = '-old' if not use_fresh else '--fresh'
  mlf_args = [MLFCLI_PROG_NAME, '-i', instrument, '-t', timeframe, use_full_arg, use_fresh_arg, '-pn', pn,'--total_lagging_periods',total_lagging_periods]
  subprocess.run(mlf_args)

  

def mx(instrument, timeframe, use_fresh=False):
  old_or_fresh = '-old' if not use_fresh else '--fresh'
  subprocess.run([MXCLI_PROG_NAME, '-i', instrument, '-t', timeframe, old_or_fresh])

def ttfmxwf(instrument, use_fresh=False):
  for t in ["M1", "W1", "D1", "H4"]:
    print(f"Processing {instrument} for timeframe {t}")
    print("  CDS....")
    cds(instrument, t, use_fresh)
    if t != "M1":
      print("  TTF....")
      ttf(instrument, t)
    if t != "M1" and t != "W1":
      print("  MX....")
      mx(instrument, t)
      
def ttfwf(instrument, use_fresh=False):
  from jgtutils import jgtcommon
  _settings = jgtcommon.get_settings()
  #ttf2run
  if hasattr(_settings, 'ttf2run'):
    ttf2run=_settings.ttf2run
  else:
    from jgtml.mlconstants import TTF2RUN_DEFAULT
    ttf2run=TTF2RUN_DEFAULT
  for pn in ttf2run:
      
    for t in ["M1", "W1", "D1", "H4"]:
      print(f"Processing {instrument} for timeframe {t}")
      print("  CDS....")
      cds(instrument, t, use_fresh)
      if t != "M1":
        print("  TTF....")
        ttf(instrument, t,pn=pn)
        
def main():
  parser = argparse.ArgumentParser(description="CLI equivalent of bash functions")
  subparsers = parser.add_subparsers(dest='command')
  
  #fxaddorder
  parser_fxaddorder = subparsers.add_parser('fxaddorder', help='Add an order')
  parser_fxaddorder.add_argument('-i','--instrument', help='Instrument')
  parser_fxaddorder.add_argument('-n','--lots', help='Lots')
  parser_fxaddorder.add_argument('-r','--rate', help='Rate')
  parser_fxaddorder.add_argument('-d','--buysell', help='Buy or Sell')
  parser_fxaddorder.add_argument('-x','--stop', help='Stop')
  parser_fxaddorder.add_argument('--demo', action='store_true', help='Use the demo account')
  parser_fxaddorder.add_argument('--pips', action='store_true', help='Use pips')
  
  #fxrmorder
  parser_fxrmorder = subparsers.add_parser('fxrmorder', help='Remove an order')
  parser_fxrmorder.add_argument('-id','--orderid', help='Order ID')
  parser_fxrmorder.add_argument('--demo', action='store_true', help='Use the demo account')
  
  #fxrmtrade
  parser_fxrmtrade = subparsers.add_parser('fxrmtrade', help='Remove a trade')
  parser_fxrmtrade.add_argument('-tid','--tradeid', help='Trade ID')
  parser_fxrmtrade.add_argument('--demo', action='store_true', help='Use the demo account')
  
  #fxtr
  parser_fxtr = subparsers.add_parser('fxtr', help='Get trade details')
  parser_fxtr.add_argument('-tid','--tradeid', help='Trade ID')
  parser_fxtr.add_argument('-id','--orderid', help='Order ID')
  parser_fxtr.add_argument('--demo', action='store_true', help='Use the demo account')
  parser_fxtr.add_argument('--nosave', action='store_true', help='Dont Save the trade details')
  
  #fxmvstop
  parser_fxmvstop = subparsers.add_parser('fxmvstop', help='Move stop')
  parser_fxmvstop.add_argument('-tid','--tradeid', help='Trade ID')
  parser_fxmvstop.add_argument('-x','--stop', help='Stop')
  parser_fxmvstop.add_argument('--pips', action='store_true', help='Use pips')
  parser_fxmvstop.add_argument('--demo', action='store_true', help='Use the demo account')
  
  #ids
  parser_ids = subparsers.add_parser('ids', help='Refresh the IDS')
  parser_ids.add_argument('-i','--instrument', help='Instrument')
  parser_ids.add_argument('-t','--timeframe', help='Timeframe')
  parser_ids.add_argument('--full', action='store_true', help='Use the full data')
  parser_ids.add_argument('--fresh', action='store_true', help='Use the fresh data')
  
  #fxmvstopgator
  parser_fxmvstopgator = subparsers.add_parser('fxmvstopgator', help='Move stop using gator')
  parser_fxmvstopgator.add_argument('-i','--instrument', help='Instrument')
  parser_fxmvstopgator.add_argument('-t','--timeframe', help='Timeframe')
  parser_fxmvstopgator.add_argument('-tid','--tradeid', help='Trade ID')
  parser_fxmvstopgator.add_argument('--lips', action='store_true', help='Use lips')
  parser_fxmvstopgator.add_argument('--teeth', action='store_true', help='Use teeth')
  parser_fxmvstopgator.add_argument('--jaw', action='store_true', help='Use jaw')
  parser_fxmvstopgator.add_argument('--demo', action='store_true', help='Use the demo account')
  
  #fxmvstopfdb
  
  parser_fxmvstopfdb = subparsers.add_parser('fxmvstopfdb', help='Move stop using fdb',epilog=fxmvstopfdb_epilog)
  parser_fxmvstopfdb.add_argument('-i','--instrument', help='Instrument')
  parser_fxmvstopfdb.add_argument('-t','--timeframe', help='Timeframe')
  parser_fxmvstopfdb.add_argument('-tid','--tradeid', help='Trade ID')
  parser_fxmvstopfdb.add_argument('--demo', action='store_true', help='Use the demo account')
  #close the trade if the stop of fdbsignal is already hit
  parser_fxmvstopfdb.add_argument('--close', action='store_true', help='Close the trade if the stop of fdbsignal is already hit')
  

  parser_tidealligator = subparsers.add_parser('tide', help='Run the pto tidealligator')
  parser_tidealligator.add_argument('-i','--instrument', help='Instrument')
  parser_tidealligator.add_argument('-t','--timeframe', help='Timeframe')
  parser_tidealligator.add_argument('buysell', help='Buy or Sell')

  parser_prep_pds_01 = subparsers.add_parser('pds', help='Refresh the PDS full for an instrument and timeframe')
  parser_prep_pds_01.add_argument('-i','--instrument', help='Instrument')
  parser_prep_pds_01.add_argument('-t','--timeframe', help='Timeframe')
  parser_prep_pds_01.add_argument('--full', action='store_true', help='Use the full data')

  parser_prep_cds_05 = subparsers.add_parser('cds', help='Refresh the CDS')
  parser_prep_cds_05.add_argument('-i','--instrument', help='Instrument')
  parser_prep_cds_05.add_argument('-t','--timeframe', help='Timeframe')
  #--fresh flag to use the fresh data
  parser_prep_cds_05.add_argument('-new','--fresh', action='store_true', help='Use the fresh data')
  parser_prep_cds_05.add_argument('--full', action='store_true', help='Use the full data')

  parser_prep_cds_06_old = subparsers.add_parser('ocds', help='Refresh the CDS from old PDS')
  parser_prep_cds_06_old.add_argument('-i','--instrument', help='Instrument')
  parser_prep_cds_06_old.add_argument('-t','--timeframe', help='Timeframe')
  parser_prep_cds_06_old.add_argument('--full', action='store_true', help='Use the full data')
  
  
  parser_prep_ttf_10 = subparsers.add_parser('ttf', help='Refresh the TTF for an instrument and timeframe')
  parser_prep_ttf_10.add_argument('-i','--instrument', help='Instrument symbol')
  parser_prep_ttf_10.add_argument('-t','--timeframe', help='Timeframe')
  parser_prep_ttf_10.add_argument('-pn','--patternname', help='Pattern Name')
  parser_prep_ttf_10.add_argument('-new','--fresh', action='store_true', help='Use the fresh data')
  parser_prep_ttf_10.add_argument('--full', action='store_true', help='Use the full data')


  
  parser_prep_mlf_22 = subparsers.add_parser('mlf', help='Refresh the MLF for an instrument and timeframe')
  parser_prep_mlf_22.add_argument('-i','--instrument', help='Instrument symbol')
  parser_prep_mlf_22.add_argument('-t','--timeframe', help='Timeframe')
  parser_prep_mlf_22.add_argument('-pn','--patternname', help='Pattern Name')
  parser_prep_mlf_22.add_argument('-tlp','--total_lagging_periods', help='Total Lagging Periods')
  parser_prep_mlf_22.add_argument('-new','--fresh', action='store_true', help='Use the fresh data')
  parser_prep_mlf_22.add_argument('--full', action='store_true', help='Use the full data')
  
  
  #ttfmxwf
  parser_post_ttfmxwf_14 = subparsers.add_parser('ttfmxwf', help='Refresh the TTF, MX and CDS for an instrument')
  parser_post_ttfmxwf_14.add_argument('-i','--instrument', help='Instrument symbol')
  parser_post_ttfmxwf_14.add_argument('-new','--fresh', action='store_true', help='Use the fresh data')

  parser_post_mx_15 = subparsers.add_parser('mx', help='Refresh the MX (using the TTF) for an instrument and timeframe')
  parser_post_mx_15.add_argument('-i','--instrument', help='Instrument symbol')
  parser_post_mx_15.add_argument('-t','--timeframe', help='Timeframe')

  parser_wf_ttf_prep_19 = subparsers.add_parser('ttfwf', help='Refresh TTF preparation for an instrument')
  parser_wf_ttf_prep_19.add_argument('-i','--instrument', help='Instrument symbol')
  parser_wf_ttf_prep_19.add_argument('-new','--fresh', action='store_true', help='Use the fresh data')
  parser_wf_ttf_prep_19.add_argument('--full', action='store_true', help='Use the full data')

  args = parser.parse_args()
  #if no arguments are passed, print help
  if not vars(args).get('command'):
    parser.print_help()
    parser.exit()

  if args.command == 'tide':
    tide(args.instrument, args.timeframe, args.buysell)
  elif args.command == 'fxaddorder':
    fxaddorder(args.instrument, args.lots, args.rate, args.buysell, args.stop, args.demo,args.pips)
  elif args.command == 'fxrmorder':
    fxrmorder(args.orderid, args.demo)
  elif args.command == 'fxrmtrade':
    fxrmtrade(args.tradeid, args.demo)
  elif args.command == 'fxtr':
    fxtr(args.tradeid,args.orderid,args.demo,not args.nosave)
  elif args.command == 'fxmvstop':
    fxmvstop(args.tradeid, args.stop, args.pips, args.demo)
  elif args.command == 'ids':
    ids(args.instrument, args.timeframe,args.full,args.fresh)
  elif args.command == 'fxmvstopgator':
    lips_value = True if not args.lips and not args.teeth and not args.jaw else False
    fxmvstopgator(args.instrument, args.timeframe, args.tradeid, lips_value,args.teeth,args.jaw,args.demo)
  elif args.command == 'fxmvstopfdb':
    fxmvstopfdb(args.instrument, args.timeframe, args.tradeid, args.demo,args.close)
  elif args.command == 'pds':
    pds(args.instrument, args.timeframe,)
  elif args.command == 'cds':
    cds(args.instrument, args.timeframe, args.fresh,args.full)
  elif args.command == 'ocds':
    ocds(args.instrument, args.timeframe)
  elif args.command == 'ttf':
    ttf(args.instrument, args.timeframe,args.patternname,args.columns_list_from_higher_tf,args.fresh,args.full)
  elif args.command == 'mlf':
    mlf(args.instrument, args.timeframe,args.patternname,args.total_lagging_periods,args.fresh,args.full)
  elif args.command == 'ttfmxwf':
    ttfmxwf(args.instrument, args.fresh)
  elif args.command == 'mx':
    mx(args.instrument, args.timeframe)
  elif args.command == 'ttfwf':
    ttfwf(args.instrument, args.fresh,args.full)

if __name__ == "__main__":
  main()
