
    'i#>                        d dl mZmZmZmZ d dlZd dlmZmZmZ d dl	Z	d dl
mZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ  G d de      Z G d dej8                        Z G d d eee            Zy)    )absolute_importdivisionprint_functionunicode_literalsN)datedatetime	timedelta)
BrokerBaseOrderBuyOrder	SellOrder)CommInfoBase)DataBase)
MetaParams)Position)with_metaclass)vcstorec                       e Zd ZdZd Zd Zy)
VCCommInfoae  
    Commissions are calculated by ib, but the trades calculations in the
    ```Strategy`` rely on the order carrying a CommInfo object attached for the
    calculation of the operation cost and value.

    These are non-critical informations, but removing them from the trade could
    break existing usage and it is better to provide a CommInfo objet which
    enables those calculations even if with approvimate values.

    The margin calculation is not a known in advance information with IB
    (margin impact can be gotten from OrderState objects) and therefore it is
    left as future exercise to get itc                     t        |      |z  S Nabsselfsizeprices      Y/var/www/app/trading-bot/venv/lib/python3.12/site-packages/backtrader/brokers/vcbroker.pygetvaluesizezVCCommInfo.getvaluesize4   s    4y5      c                     t        |      |z  S )z9Returns the needed amount of cash an operation would costr   r   s      r   getoperationcostzVCCommInfo.getoperationcost8   s     4y5  r    N)__name__
__module____qualname____doc__r   r"    r    r   r   r   &   s    )!!r    r   c                        e Zd Z fdZ xZS )MetaVCBrokerc                 Z    t         t        |   |||       | t        j                  _        y)z+Class has already been created ... registerN)superr)   __init__r   VCStore	BrokerCls)clsnamebasesdct	__class__s       r   r,   zMetaVCBroker.__init__?   s$     	lC)$s;$'!r    )r#   r$   r%   r,   __classcell__r3   s   @r   r)   r)   >   s    ( (r    r)   c                        e Zd ZdZdZ fdZ fdZ fdZd ZddZ	d Z
d	 Zd
 ZddZd Z	 	 	 d dZd Z	 	 d dZ	 	 d dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z xZ S )!VCBrokera  Broker implementation for VisualChart.

    This class maps the orders/positions from VisualChart to the
    internal API of ``backtrader``.

    Params:

      - ``account`` (default: None)

        VisualChart supports several accounts simultaneously on the broker. If
        the default ``None`` is in place the 1st account in the ComTrader
        ``Accounts`` collection will be used.

        If an account name is provided, the ``Accounts`` collection will be
        checked and used if present

      - ``commission`` (default: None)

        An object will be autogenerated if no commission-scheme is passed as
        parameter

        See the notes below for further explanations

    Notes:

      - Position

        VisualChart reports "OpenPositions" updates through the ComTrader
        interface but only when the position has a "size". An update to
        indicate a position has moved to ZERO is reported by the absence of
        such position. This forces to keep accounting of the positions by
        looking at the execution events, just like the simulation broker does

      - Commission

        The ComTrader interface of VisualChart does not report commissions and
        as such the auto-generated CommissionInfo object cannot use
        non-existent commissions to properly account for them. In order to
        support commissions a ``commission`` parameter has to be passed with
        the appropriate commission schemes.

        The documentation on Commission Schemes details how to do this

      - Expiration Timing

        The ComTrader interface (or is it the comtypes module?) discards
        ``time`` information from ``datetime`` objects and expiration dates are
        always full dates.

      - Expiration Reporting

        At the moment no heuristic is in place to determine when a cancelled
        order has been cancelled due to expiration. And therefore expired
        orders are reported as cancelled.
    ))accountN)
commissionNc           
         t         t        |           t        j                  di || _        d | _        dx| _        | _        dx| _	        | _
        t        j                         | _        t        j                  t               | _        t        j                         | _        t'               | _        t        j*                         | _        t.        j0                  | j
                  j2                  j4                  t.        j6                  | j
                  j2                  j4                  t.        j8                  | j
                  j2                  j:                  t.        j<                  | j
                  j2                  j>                  t.        j@                  | j
                  j2                  jB                  i| _"        t.        jF                  | j
                  j2                  jH                  t.        jJ                  | j
                  j2                  jL                  i| _'        t.        jP                  | j
                  j2                  jR                  t.        jT                  | j
                  j2                  jV                  t.        jX                  | j
                  j2                  jZ                  t.        j\                  | j
                  j2                  j^                  i| _0        t.        jb                  | j
                  j2                  jd                  i| _3        | j
                  jh                  jj                  | j
                  jh                  jl                  | j
                  jh                  jn                  f| _8        y )N        r'   )9r+   r7   r,   r   r-   store	_acc_namestartingcashcashstartingvaluevalue	threadingLock	_lock_poscollectionsdefaultdictr   	positions_lock_ordersdict	orderbyiddequenotifsr   Marketvcctmod	OT_MarketCloseLimitOT_LimitStopOT_StopMarket	StopLimitOT_StopLimit_otypesBuyOS_BuySellOS_Sell_osidesT_NoneTR_NoRestrictionT_DateTR_DateT_CloseTR_CloseAuctionT_Day
TR_Session_otrestrictionV_NoneVR_NoRestriction_ovrestrictionvcdsmod	IT_Future	IT_OptionIT_Fund	_futlikes)r   kwargsr3   s     r   r,   zVCBroker.__init__   s5   h&(__.v.
 (++DI*--TZ #)$00: &NN, "'') LL$**,,66KK++55KK++44JJ

**88OOTZZ//<<
 IItzz))00JJ

**22
 LL$**,,==LL$**,,44MM4::--==KK++66	
 LL$**,,==

 JJ(($***<*<*F*FJJ&&
r    c                 b    t         t        |           | j                  j                  |        y )N)broker)r+   r7   startr<   r   r3   s    r   rq   zVCBroker.start   s%    h#%

%r    c                 ^    t         t        |           | j                  j                          y r   )r+   r7   stopr<   rr   s    r   rt   zVCBroker.stop   s    h"$

r    c                     | j                   S r   )r?   r   s    r   getcashzVCBroker.getcash   s    yyr    c                     | j                   S r   )rA   )r   datass     r   getvaluezVCBroker.getvalue   s    zzr    c                 6    | j                   j                         S r   )rL   popleftrv   s    r   get_notificationzVCBroker.get_notification   s    {{""$$r    c                 V    | j                   j                  |j                                y r   )rL   appendclone)r   orders     r   notifyzVCBroker.notify   s    5;;=)r    c                 :    | j                   j                  d        y r   )rL   r   rv   s    r   nextzVCBroker.next   s    4 r    c                     | j                   5  | j                  |j                     }|r|j                         cd d d        S 	 d d d        |S # 1 sw Y   S xY wr   )rD   rG   
_tradenamer   )r   datar   poss       r   getpositionzVCBroker.getposition   sR    ^^ 	#..1Cyy{	# 	#	#
 
	#
 
s   +AAc                    |j                   | j                  v r| j                  |j                      S | j                  d    }||S |j                  j                  | j                  v }t        |j                  j                  |      S )N)mult	stocklike)r   comminfo_syminfoTyperm   r   
PointValue)r   r   r   r   s       r   getcommissioninfozVCBroker.getcommissioninfo   sm    ??dmm+==11==&OMM&&$..8	t}}779MMr    c
                    | j                   j                  j                         }| j                  |_        |j
                  |_        | j                  |   |_        | j                  |   |_
        | j                  t        j                     |_        d|_        d|_        d|_        |	rdj#                  |	      |_        nd|_        t'        |      |_        d|_        d|_        |t        j.                  k(  rno|t        j0                  k(  r|xs ||_        nP|t        j2                  k(  rn<|t        j4                  k(  r||_        n!|t        j6                  k(  r||_        ||_        d |_        |t        j2                  k(  r$| j:                  t        j<                     |_        n|#| j:                  t        j@                     |_        ntC        |tD        tF        f      r*| j:                  t        jH                     |_        ||_        ntC        |tJ        f      ru|t        jL                  k(  r#| j:                  t        jN                     |_        nm| j:                  t        jH                     |_        tE        jP                         |z   |_        n.| jR                  s"| j:                  t        jN                     |_        |
D ]  }tU        ||      stW        |||
|          ! |S )Nr    z
TradeId {}r;   ),r<   rN   r   r=   Accountr   
SymbolCoderW   	OrderTyper\   	OrderSiderh   rf   VolumeRestriction
HideVolume	MinVolumeUserOrderIdformatExtendedInfor   Volume	StopPricePricerM   rQ   rP   rS   rU   	ValidDatere   ra   TimeRestrictionr]   
isinstancer   r   r_   r	   DAYrc   nowvalidhasattrsetattr)r   ordtypeownerr   r   r   plimitexectyper   tradeidrn   r   ks                r   
_makeorderzVCBroker._makeorder   s7   
 

""((*??,,x0,,w/"&"5"5ell"C !-!4!4W!=E!#E4yu||#$/6EK$##EO(#EO EKu{{"$($7$7$FE!}(,(;(;ELL(I%EHd#34(,(;(;ELL(I%"'EI<0EII%,0,?,?,LE),0,?,?,ME)&.llnu&<EOZZ(,(;(;EKK(H%  	-Aua q&),	- r    c                 6   |j                  |        |}| j                  j                  j                  |j                  |j
                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  
      }||_        |j                  | j!                  |j"                               | j$                  5  || j&                  |<   d d d        | j)                  |       |S # 1 sw Y   xY w)N)r   )submitr<   vcct	SendOrderr   r   r   r   r   r   r   r   r   r   vcorderaddcomminfor   r   rH   rJ   r   )r   r   r   vcooids        r   r   zVCBroker.submit#  s    Tjjoo''KKMM3==#**cii!!3#6#6mm	 ( 
 $00<= 	("'DNN3	(E	( 	(s   $DDc	                     t        ||||||||      }
 |
j                  di |	  | j                  |
j                  ||||||||f	i |	}| j	                  |
|      S N)r   r   r   r   
pricelimitr   r   r   r'   )r   addinfor   r   r   r   r   r   r   r   r   r   r   r   rn   r   r   s               r   buyzVCBroker.buy6  sv    
 u4"%F"*%J 	!$//%--dE"((E7,$*, {{5'**r    c	                     t        ||||||||      }
 |
j                  di |	  | j                  |
j                  ||||||||f	i |	}| j	                  |
|      S r   )r   r   r   r   r   r   s               r   sellzVCBroker.sellG  sv    
 D#5V#+5'K 	!$//%--dE"((E7,$*, {{5'**r    c                 X   || _         |j                  D ]  }| j                  j                  $| j                  j                  |j                  k(  s=|j
                  j                  x| _        | _        |j
                  j                  x| _
        | _        |j                  | _         | S  | S r   )traderAccountspr8   r   BalanceCashr>   r?   NetWorthr@   rA   r=   )r   r   accs      r   __call__zVCBroker.__call__[  s     ?? 	Cvv~~%3;;)F030@0@@!DI25++2F2FF"TZ!$	 r    c                     | j                   | j                   |k7  ry | j                  j                  D ]I  }|j                  |k(  s|j                  j
                  | _        |j                  j                  | _         y  y r   )	r=   r   r   r   r   r   r?   r   rA   )r   r   r   s      r   OnChangedBalancezVCBroker.OnChangedBalancei  sd    >>!T^^w%>;;'' 	C{{g%KK,,	 [[11
	r    c                      y r   r'   r   r   s     r   OnModifiedOrderzVCBroker.OnModifiedOrdert  s     	r    c                     | j                   5  	 | j                  |j                     }	 d d d        j	                          | j                  |       y # t        $ r Y d d d        y w xY w# 1 sw Y   BxY wr   )rH   rJ   OrderIdKeyErrorcancelr   r   r   borders      r   OnCancelledOrderzVCBroker.OnCancelledOrdery  sl     	6	 	F	  		 		 	(   A*A	A'A*&A''A**A3c                 *    | j                  |d       y )NFpartialOnExecutedOrderr   s     r   OnTotalExecutedOrderzVCBroker.OnTotalExecutedOrder  s    UE2r    c                 *    | j                  |d       y )NTr   r   r   s     r   OnPartialExecutedOrderzVCBroker.OnPartialExecutedOrder  s    UD1r    c                 J   | j                   5  	 | j                  |j                     }	 d d d        |j                  }|j
                  }j                         r|dz  }| j                  |j                  d      }|j                  }|j                  ||      \  }}	}
}|j                  }|j                  ||      }|j                  ||      }|j                  |
|      }|j                  |
|      }|j                  | ||      }|j                  ||      }|j!                  |j                  j"                  d   ||||||
||||||	       |r|j%                          n|j'                          | j)                  |       y # t        $ r Y d d d        y w xY w# 1 sw Y   qxY w)NF)r   r   )rH   rJ   r   r   r   r   issellr   r   r   updater   r"   getcommissionprofitandlossr   executer   r   	completedr   )r   r   r   r   r   r   positionpprice_origpsizeppriceopenedclosedr   closedvalue
closedcommopenedvalue
openedcommpnlmargins                      r   r   zVCBroker.OnExecutedOrder  s    	6	 ||==?BJD ##FKKu#=nn(0e(D%vvv??//D++FE:
//>++FE:
$$fWk5A&&tU3 	v{{++A.U{J{Jsf	& NNFK  		 		 	s(   FF	F
FFFF"c                     | j                   5  	 | j                  |j                     }	 d d d        j	                          | j                  |       y # t        $ r Y d d d        y w xY w# 1 sw Y   BxY wr   )rH   rJ   r   r   acceptr   r   s      r   OnOrderInMarketzVCBroker.OnOrderInMarket  sl     	6	 	F	  		 		 	r   c                      y r   r'   r   s     r   OnNewOrderLocationzVCBroker.OnNewOrderLocation      r    c                      y r   r'   r   r   s     r   OnChangedOpenPositionszVCBroker.OnChangedOpenPositions  s    
 	r    c                      y r   r'   r   s     r   OnNewClosedOperationszVCBroker.OnNewClosedOperations  r   r    c                      y r   r'   rv   s    r   OnServerShutDownzVCBroker.OnServerShutDown      r    c                      y r   r'   )r   p1p2p3s       r   OnInternalEventzVCBroker.OnInternalEvent  r   r    r   )T)NNNNr   )!r#   r$   r%   r&   paramsr,   rq   rt   rw   rz   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r4   r5   s   @r   r7   r7   F   s    6nF
1
f&%*!
N -1(,?B( &*/0+$ '+01+(	
32)V	r    r7   )
__future__r   r   r   r   rE   r   r   r	   rB   
backtraderr
   r   r   r   backtrader.comminfor   backtrader.feedr   backtrader.metabaser   backtrader.positionr   backtrader.utils.py3r   backtrader.storesr   r   r3   r)   r7   r'   r    r   <module>r     sh   ** *  . .  = = , $ * ( / %! !0(:'' (L~lJ7 Lr    