unit tests]IDE

i accept the need for individual tests for each important method. Background: IDE is necessity in the team.

Option 0: main method for now, unit test cases later
Option 1: junit

Tests are so frequently run that i don’t like the extra step of opening the test class. Using main method, i don’t have to.

i change my methods often. if i invest effort building the unit tests, the effort can be wasted. Perhaps build those methods after the initial volatile phase.

Too many classes open.

Advertisements

sybase trigger — unique id column

specific Purpose: input validation. Let’s zoom in on this. insert, update. not delete.

My observation: a unique id column is important to any input-validation trigger in sybase.

My reasons: you usually need UPDATE yourtable set …. WHERE yourtable.id=inserted.id. Without the where-clause, you could update pre-existing rows. Perhaps millions of pre-existing rows for every row inserted.

Because sybase doesn’t support before-trigger, you need this trick to update the rows just inserted.

FX settlement system

I once interfaced with the FX settlement (clearance) system of a major US bank (let’s call it CB). There are always 2 counterparties to each trade. Each counterparty has a nostro account with an “clearance bank” [1]. The settlement process must transfer one currency from clearance bank acct A to clearance bank acct B, and transfer the other currency from B to A.

For example, JPM could be a counter party, but for one particular FX trade, the HKD clearance bank could be HSBC in Hongkong.

In our case, one of the 2 clearance banks is always CB itself. In fact one of the 2 counter parties is usually a CB-controlled trading account.

The settlement system is also know as “cash manager”.

[1] For example nostro acct to receive HKD must exist in a HK bank — the nostro bank. Only HK banks can be the clearance bank for HKD. In the special case of Euro, nostro acct can be in any Eurozone country.

input-validation triggers — sybase

A few websites say that “at the time of writing, sybase has no before-trigger”, like Oracle, mysql or DB2.

Solution? you know the new values are already in the table, but u can UPDATE those new values and commit, or make an explicit rollback. This would ensure only valid data get committed.

a class HAS-A instance of the same class

The /casual/ observer encounters many patterns where Object1.java HAS-A instance of Object1.

if the nested instance is a static instance (static member or a local var in a static block), … i feel there’s no OO principle behind the pattern. The hosting object (a class object) and the nested object are very different — class object vs instance of Object1.

From now on, we exclude static instances.

If a domain object follows this pattern, usually(?) there’s a real-world relationship to explain it. Perhaps a parent HAS-A child, a course has a pre-requisite course, a company has an institutional shareholder …

boolean column ] database@@

Q: how to you design your table columns to hold boolean flags such as isOK, isAlive, isActive, which are heavily used in where? The challenge is, no index possible, at least in sybase =} FTS. For now, assume you want to select the minority of the rows. If you want the majority, then FTS may be legitimate.

A: Basically you only care about yes/no. But I would suggest use 0 for the majority of the rows, and 1-255 or 1 ~ FFFF for the minority. Keep this column narrow — 1 or 2 bytes, then build an index.

Even though ms sql and mysql can perhaps create an index on a binary or BIT column, it’s 1) less well-supported than regular indices and 2) questionable. In an enterprise enviroment, politically safer to stick to regular indices.

http://www.sql-server-performance.com/article_print.aspx?id=347&type=art has examples.

http://sqlserver2000.databases.aspfaq.com/can-i-create-an-index-on-a-bit-column.html has examples.

best way to sanity-check java method arguments?

Say you are writing a utility Class1.getByIndex(int arrayIndex). Best way to enforce that arrayIndex is positive?

– throw an unchecked error and crash the jvm? Recommended by many experts. I guess the downside is tolerable, and there are no better candidates as a standard, universal solution.
– throw a checked exception and force other programmers to try-catch? I think the overhead grows when you set this as standard practice.
– return a boolean result? Many methods/constructors can’t.

Ideally, you want to remind other programmers to check their input first, but not force them to put up a useless try-catch.

how to instantiate a new java Date object

Q: how to instantiate a new java Date object with 3 numbers for year, month and date?

I guess Calendar could be one standard solution, but not a one-liner.

Practical solution for the time being: use the deprecated constructors

— new java.util.Date?

Only deprecated constructors do that.
java.sql.Date.valueOf(“2008-04-02” )

–new java.sql.Date?

Only deprecated constructors do that.
java.util.Date.getTime() can feed a long to a java.sql.Date() constructor

SQL-CASE expressions — keywords

* evaluate — each case expression evaluates to a …
* per-row — the expression is usually evaluated for each row
* if-then-else

All above keywords apply to both simple and searched case expressions

which parts of the case expression can be “expanded”?
– when clause
– after-case expression, right after the “CASE” keyword
– ??? then clause

Where can a case-expression appear?
* group-by
* update->set
* select-columns

python introspection – speculation+observations

Background — Python’s 2 fundamental features, introspection and polymorphism, appear to be integrated (more than in other languages). You could add to the mix the “module” feature, but I won’t.

The __dict__ thingy seems to be the common theme (heart of everything python), but I found it hard to prove in code. For now, let’s take [[Programming python]] at face value.

Python introspection offers perhaps the best window into python internals. I guess introspection reveals
– polymorphism, inheritance,
– function call resolution (always run time)
– instance-method/class-method
– bound methods
– user defined functions and classes
– modules and namespaces

Here’s a limited sample of the numerous introspection features in python —
– __dict__
– __methods__, __members__
– dir()
– type()
– isinstance()
– __mro__

MVC+dispatcher, in a purist design

See other posts on this blog about spring, struts …

In a purist MVC design, elements below get less and less purist as we move down the list, so I usually spend more time on the first few layers to keep them well-behaving, well-defined and well-understood.

* model — the model in ModelAndView is just a Map, allowing the use of multiple objects keyed by name. In general, “model” means domain model in the form of beans. These classes should not import or depend on controller or view classes. I believe a lot of business logic can go into the models, because it is the behavior of the domain models.

What if some low-level logic is shared between a model and a controller (or something below)? We risk tight coupling if a model imports a class, which in turn imports the controller. Solution: make that utility independent of models or controllers.

* view — should have as little logic as possible. Ideally, views can change in response to controller, so the biz logic lies outside the view — examples include hiding input fields.

View classes need to import model classes, but seldom controller classes. Since controllers control views, it’s a sign of tight coupling if views start to import controller classes. You end up with a entangled architecture — poor separation of concern.

* front dispatcher — usually required. Struts and spring.

* sub-controllers — for each operation or action, such as login, CRUD.

* helper classes but excluding well-defined beans — the miscellaneous. Nothing purist about these. MVC pattern won’t help you much here, but other patterns might.

exit status, if/while, test, &&, ||

I think most if not all shell boolean-constructs evaluate an exit-status. Here are an incomplete list of boolean-constructs — ie constructs about yes/no. Unifying them all, the 2 unifying factors are boolean and exit-status, right?

autosys failure/success? yes
the shell’s IF construct? This is the simplest, base case.
WHILE? same as IF
TEST? same as []
[]? yes. IF [ something ] evaluates the exit status of [ something ]
&& , || ? yes

See other post(s) on exit status

dynamic_cast, typeid(*ptr) and vtbl

An interviewer pointed out if a pair of derived/base classes have no virtual function, then you can’t dynamic_cast between them even using pointers and references.

RTTI is inapplicable to types without vtbl, because such types are always fixed and known at compile time. For example D extends B, without any virtual method. We create a D object but give its address to a B pointer. What’s the typeid of the _unwrapped_ pointer? It’s a B. See post on AddressOfBasement.

#include
class base{
public: //virtual
    ~base(){}
};
struct derived: public base{};
int main(){
    base* p = new derived();
    cout<<typeid(*p).name(); // prints DERIVED if "virtual"; prints BASE otherwise 
    cin.get();
}

Also note
– a struct can extend a class, and vice versa
– dtor must be public to compile

sybase dbo and ownerships

based on http://www.benslade.com/tech/OldIntroToSybase/security.html

Database tables, stored procedures, etc. are owned by users in a database — regular developer accounts or special accounts. Full syntax for referring to a table, view, or stored procedure is [1]:

database.owner.object

There is a special (different from regular login accounts) user in each database called the database owner or “dbo”. The dbo has all privileges within her own database. Each database has one and only one “dbo” user.

The database owner (dbo) can also own objects. In most production environments, the dbo (rather than developer users) owns the tables and stored procedures in a database. This is to preempt developer resignation (or passing away:(

[1] I think in many systems “owner” is omitted cos there’s no other owner beside dbo. In other systems, for the owner the current login session’s database name (??) is used as a first choice. The dbo is used as the second choice

ptr-ref layering #reference to pointer

Update http://markgodwin.blogspot.sg/2009/08/c-reference-to-pointer.html is a detailed blog post

Background — I doubt you ever need to know these arcane data types, but these are at work whenever you specialize a class template using a pointer as the “T”.

int * ptr2int;
int * & ref2ptr = ptr2int; // ok

int **** ptr;
int ****& ref = ptr; // ok

Real Case in point from EffC++ : The default allocator of vector (and many containers) has a nested typedef for T* (called “pointer”) and a nested typedef for T& (called “reference”). Now if you instantiate a vector using a reference type as the “T”, you die, because

The pointer typedef won’t compile, because you can’t declare a pointer to a reference; [1]
The reference typedef won’t compile, because you can’t declare a reference to a reference.

However, You can have a ref to a pointer to a pointer to a pointer to a pointer….

[1] However, we often take address of a reference variable. See https://bintanvictor.wordpress.com/2012/04/04/convert-a-reference-variable-to-a-pointer-variable/

Now the rule on reference-pointer layering –

  • If you start with a nonref variable, you can add “pointer” layers over and over, but any “reference” layer must be the last layer.
  • In other words, once you “reference” anything, you can’t layer on top of it.
    • You can declare a variable “pointing to” anything, so long as there’s not already a reference layer
    • You can declare a variable “referencing” anything, so long as there’s not already a reference layer
    • Pointer-to-reference is illegal as a variable type, but you can take the address of a reference!

 

variable-scope vs object-lifetime

(See also blog post on [[a heap-stack dual variable]].)

[[OO MutliThreading using c++]] P 355 lists 4 scopes.

Sound byte — any object’s address is always immutable. It’s a simple, fundamental concept but not always obvious to me:)

Sound byte — a pointer (and a java reference) variable is a 32bit memory location[3] with a _permant_name_. This 32bit object is the 32bit pointer itself. When you reseat the pointer, you change the state of this 32bit pointer object, but this 32bit pointer object stays at the old address.

[3] often on stack, even if the pointee is on heap)

Q: A fully qualified var name is unique by definition. Mem addresses are unique by definition. How are they related?
* A stackVar has a name attached to the address. Is the name->address mapping permanent? I think so.
** what if the stackvar is a ptr to a heap object? 4-byte ptr is on stack? yeah
* A c++ ref is a permanent name permanently attached to an address, even after the address is reclaimed (ref becomes invalid) Think Unix symlink.

* a heap object is always nameless. When created, new() returns the address only. Can you ever attach a name to that address? i doubt it. You can attach multiple pointers and name the pointers, which have 4-byte addresses. Heap holds unnamed addresses. Think Unix Hardlink.

* java objects are always nameless. An object (address immutable) has no names attached to address. Name is for the variable, which can be reseated to another address. Unix hardlink. Just like pointers.

[[c++ primer]] says variables have scope and objects have lifetime.
* Simple stackVar has matching scope/lifetime. When a regular stackVar goes out of scope, the object goes.
* static locals have small scope and long lifetime
* fields have class scope, and same lifetime as host object??
* heap objects are complicated — long life and no scope. A heap object is associated with zero[2] or more pointer variables. Usually a ptr variable is a stackVar or a field. The 4-byte pointer object has its own lifetime and a variable scope. If heap obj links to just one ptr variable, and it goes out of scope and 4-byte reclaimed, we get leaks.

[2] zero means unreachable object and a leak

2D-array-variable vs double-ptr-variable – c++

[1] Consider a strict 2D-array-variable declared as
int myArray[9][9]; // size? exactly 81 ints + 9 pointers. Are the 81 locations contiguous? Yes for a 2D array.

For a 1D array of pointers (probably same as jagged array), Not contiguous. The 1st (contiguous 9 ints) can live far from the 2nd (contiguous 9 ints). http://stackoverflow.com/questions/7784758/c-c-multidimensional-array-internals has the syntax

Any array is fix-sized (in theory). If you want to append physically, the physical memory block past the end of your array may not be available :-(.

So What solutions can you imagine?
P101 [[c pointer & mem mgmt]] shows diagrammatically a very common solution using a double pointer. Note a 2D-array variable won’t work here.

Once you allocate every nested array in the strict 2D structure, its memory usage is fixed, as it will look like [1] above?? I don’t think so. It’s more like the jagged 2D of C#. The declaration of myArray in [1] restricts the physical capacity of all the sub-arrays. In contrast, for a variable declared as a double-pointer, now I can point it at myArray, and later I can reseat it to an int[8][8].

I can also reseat my double-ptr at a partially initialized 1D array (size 5) of pointer objects, where the last pointer object is null. I can then point that last pointer to an int[99].

Now we realize a strict 2D-array-variable and a double-pointer-variable are quite different.

PCP, intuitively, +! Fwd contract

The notations C, P, F are very ambiguous. F means what? MV of an existing fwd position?

Tip — either think in terms of terminal value of pre-expiry. Don’t mix them
Tip — think of owning the underlier (or a fully-paid fwd position). The standard Fwd position’s MV and PnL are … non-intuitive and confusing to me.Tip — think in terms of change in MV. MV itself is poorly defined. See post on MktVal confusion. PnL is also confusing due to the fee paid upfront…

Tip — don’t bother with the innocent-looking details of some “fwd struck at K”. It’s not so simple, after you deal with it for 5 years, and the complexity is unneeded, when we can use a fully-paid fwd position.
Tip — either think of premium paid (and locked in) or think of pre-expiry live PnL of existing positions. Don’t mix them.
Tip — don’t bother with the premium paid in the past. That amount is just a can of worm that gives nothing but confusion. The only premium thing relevant here is the value of an advertized option.

PCP assumes 0 bid/ask and 0 commission. Let’s consider the most liquid family — Eur/Usd or SPX index. The option bid/ask is large.

For a beginner, this non-trivial concept is simplified by substituting a fixed amount of cash for the bond.
http://www.theoptionsguide.com/understanding-put-call-parity.aspx has a nice diagram to illustrate the call portfolio vs the put portfolio. When studying any payoff diagram, #1 key point to bear in mind is that the X-axis is the possible underlying asset prices at_expiration. X-axis is not time. Time is irrelevant in the PCP analysis if we use cash to substitute the bond. Now let’s focus on an intuitive illustration of the call-put parity.

(In this first exmple, let’s assume an option contract has just 1 share, rather than the 100 shares in real contracts.)

A portfolio of 1 share of IBM + 1 put at $100 (Protective put — original motivation of PUT contracts and its simplest usage.)

Suppose our PUT is deep in the money, and IBM is trading at $77. Portfolio value is simply $100, since we have the right to cash in our share at $100. When IBM trades at $111, portfolio is worth $111.This payoff is equivalent to a call (K=100)+ $100 cash. In terms of terminal MV,

   K (i.e. cash) + C = P + S (i.e. underlier, paid in full)

In this illustration, we completely avoid the (confusing) fwd or futures contract. Instead, we deal with options and underlier asset only, so the MV concept is clear.

This relation holds at expiry. By arbitrage argument, it also holds any time before maturity.
—— There’s a simpler version involving just 3 trades
* Suppose I buy an $100 ATM Put for $9 and also buy 100 IBM at the current price of $100/share.(A protective put?)
* My friend buys the $100 ATM Call also at $9. (No surprise the ATM call and put have identical valuations.)
* We both start with $10900 cash.

After the purchase, my portfolio has $0 cash + the put + the stock; my friend has $10000 cash + the call.

At expiration, Our 2 portfolios are identical. In this version, you don’t see the bond position!

—— Now let’s try to make sense of PCP with a fwd but no bond. Let’s try to simplify the fwd contract. There are many standard ways to define it. As a holder, an “K-based fwd” [5] requires me to pay a fixed price $K (eg $100) at expiry to receive the asset. No upfront payment.
pnl at expiry = S_T – K, which could be negative
pnl at a time before expiry = S – K, which could be negative
MV is … defined as same as pnl. It’s non-intuitive.

   C = P + F(K)

where C and P mean the strictly positive MV of the call/put, ignoring the premium paid, and F(K) means the +/- MV of the K-based fwd contract.

The expiration range-of-possibility graph would show the RHS is the same hockey stick as the call… same terminal payoff.

This relation holds at maturity. By arbitrage argument, it also holds any time before maturity.

[5] “K-based fwd”, denoted F(K) means an off-market fwd contract struck at K. The on-market fwd has a strike price equal to the fair fwd price. In FX, the on-market fwd contract is struck at the fwd rate.

autosys box vs command

Q: generally, should we put start-conditions (timing or job-dependencies) on the box or on a command-job?
A: box

Q: my box has a time condition such as calendar, day of the week, start_times. What if my child job has another time condition?
A: not best practice, but works

Q: How do I send repeated, half-daily alerts until a file (/tmp/abc.txt) arrives please? We want it from last Monday of each month till 3 days later.

Q: what happens I specify no start condition (timing or job-dependencies) on the box, only on the child jobs?

start/end of a unit of work — DB2

J4: it’s important to understand this (simple) concept when reading about savepoints, ….

Practically, at any (except right after a commit/rollback) moment in your session, you are in an open[1] transaction.

The DB2 trainer said a tx would start when u are outside any tx and issue a select or another sql statement. I still don’t understand.

[1] or “active transaction”

database access control solutions for enterprise

solution: deny access to command line tools like sql+ or sqsh, deny access via standard windows clients like toad, aqua studio. Require every interactive user to access via a browser.

solution: custom api for java clients. block access via jdbc.

Solution: views to limit access to subset of rows, subset of columns or derived columns. deny access to underlying tables.

Solution: sproc and function to limit access. deny direct access to underlying tables. I think this is the most flexible.

favor narrow index keys

According to the DB2 trainer, narrow index keys are always better. Many principles in DB tuning have exceptions, not this one. The wider the key, the fewer entries per node page, the more layers in the B+tree, the more disk reads. Each layer usually [1] translates to one disk read.

Usually a point search on the index starts from the root, and reads one node per layer.

How wide is an index key? I asked the DB2 trainer. It’s pretty much the width of each index column added together. Compression on the width is doable.

[1] often the root node and the first layer are in memory and requires no disk read. Remember there are easily hundreds of indices in a machine.

Merrill S’pore: fastest stock broadcast

Updates — RV or multicast topic; msg selector

I think this is a typical wall-street interview question for a senior role. System requirement as remembered by my friend the interviewee: ML needs a new relay system to receive real-time stock updates from the stock exachange such as SGX. Each ML client, one of many thousand[1], will each install a new client-software [3] to receive updates on the stocks [2] she is interested. Some clients use algorithmic trading system and need the fastest feed.

[1] Not clear about the order of magnitude. Let’s target 10,000
[2] Not clear how many stocks per client on average. Let’s target 100.
[3] Maintence and customer support for a custom client-software is nightmare and perhaps impractical. Practically, the client-software has to be extremely mature such as browsers or email clients.

Q: database locking?
A: I don’t think so. only concurrent reading. No write-contention.

Key#1 to this capacity planning is how to identify bottlenecks. Bandwidth might be a more severe bottleneck than other bottlenecks described below.

Key#2 — 2 separate architectures for algorithmic clients and traditional clients. Each architecture would meet a different minimum latency standard, perhaps a few seconds for traditional and sub-second for algorithmic.

Solution 0: Whatever broadcasting system SGX uses. In an idea world, no budget constraint. Highest capacity desired.

Solution 2: no MQ? No asynchronous transmission? As soon as an update is received from SGX, the relay calls each client directly. Server-push.

Solution 1: MQ — the standard solution in my humble opinion.

Solution 1A: topics. One topic per stock. If 2000 clients want IBM updates, they all subscribe to this topic.

Q: client-pull? I think this is the bottleneck.

Q: Would Client-pull introduce additional delays?

Solution 1B: queues. one queue for each client each stock.

If 2000 clients want IBM updates, Relay need to make that many copies of an update and send to that many queues — duplication of effort. I think this is the bottleneck. Not absolutely sure if this affects relay system performance. Massively parallel processing is required, with thousands of native CPU threads (not java green threads)

c++ header file == #define@@

Whenever you see ANY “header file”, think of #define. It’s the same copy-paste process. It’s the same pre-processor. You ship object files not header files to your users, because header files are not referenced at runtime.

———- Forwarded message ———-
From: Chuck

Hi,

  The trick to header files is that they are nothing but string substitution. If you copied the contents of the header inline in the file where the include directive is, you get exactly the same result. One little trick that can help is, the compiler will take an argument that tells it to preprocess only (‘-E’ I think in g++). You’ll see what the expanded headers and macros look like with that option.

joining an existing transaction

an EJB method has 6 transaction attributes (described in tref). A basic concept is “joining a transaction”. It means “joining an existing transaction”.

This joining concept is important not only in EJB.

According to the DB2 trainer, DB2 triggers and functions JOIN transactions, whereas sproc often CONTROL transactions. Let’s explore

* a function is used in a single select.
* a trigger is invoked as part of a CUD

sybase c++ self-quiz

See http://manuals.sybase.com/onlinebooks/group-cnarc/cng1110e/dblib/@Generic__BookTextView/503;pt=505#X

Q:2 standard header files?
A: 1) sybfront.h, 2) sybdb.h, as seen in MTS include files

Q: where are the custom structs defined?
A: sybfront.h — also includes type definitions for datatypes that can be used in program variable declarations

Q: what must be the first DB-Library/C routine in the program?
A: dbinit() – This routine initializes DB-Library/C. It must be the first DB-Library/C routine in the program

Q: how is the “dbproc” object set up?
A: dbinit -} dblogin -} dbopen
Let’s look at dbopen() – The dbopen routine opens a connection between the application and a server and creates the dbproc object. It uses the LOGINREC supplied by dblogin to log in to the server. It returns a DBPROCESS (dbproc) structure, which serves as the conduit (or handle/connection/session) for information between the application and the server. After this routine has been called, the application is connected with SQL Server and can now send Transact-SQL commands to SQL Server and process any results.

Q: dbcmd() vs dbsqlexec()?
A: buffer building vs GO

triggers for input-validation

Use a BEFORE-trigger, not an AFTER-trigger or INSTEADOF-trigger.

Input-validation often contains real business logic (age > 18). The same business logic must go into app, perhaps javascript too.

Q: Maintenance nightmare?
A: No. Some input come through the app, some input come through a DBA tool

most common types of OO classes

There are many types of classes you encounter as an OO designer, such as when you study design patterns. Here are some common types of classes — we are not saying “objects”.

* domain objects — classes representing real-world entities specific to your business domain, including abstract things like a reimbursement, enrollment. FTTP projects is typical. “data-model-object” is the term used in [[ hardcore java ]]

* data objects — typically one class for one db table, one object for one row.

* state+operation object (s+o objects) — a class primarily made up of state variables, with operations defined /based-on/ the object state.

* Software-engineering objects — No better name. These classes have no real-world counterparts. These classes were written purely for software engineering. Eg: wrapper, adapter, connection, message-receiver, controller, DAO …

Some less common types of classes:
* process-objects — modeling a real process, in workflow applications …

IDE step-through — tips

Background: Step-through is one of the biggest j4IDE.

ans = invoke( obj1.method2(obj3.method4)….)
Problem: impractical to step-through this code.

Solution: use local vars to ensure every line mentions a single method. You can now step through each method. You can also inspect the local vars!

Date d1=prcdate.getTime();
Date d2=DateTimeUtils.maxTime(prcdate.getTime());
TaskQueue ctq = getTaskQueue(d1, d2);
ans = invoke( ctq);

Even the last line would be “stepped on” twice (exactly?). The stepper would stop before the call, and stop again before assignment.

tiny sql database embedable in java

http://robsanheim.com/2006/03/10/searching-for-the-perfect-in-memory-database/ mentions derby, hsql, sqllite

I think this kind of thing might be relevant to our systems:

status-quo: We have sybase/udb. I think we use temp tables or staging tables to hold temporary data. a little slow.

status-quo: We create custom objects (java collections) to hold stuff in memory, but need to build custom-methods to access them. A pain to test. Great if we can use standard sql instead of those methods. The idea is to leverage on existing standard and avoid custom coding to duplicate existing standard.

We have lots of feeds.

FX fwd outright^swap, rolling fwd, repo…briefly

There are 2 instruments in FX forward. Forward outright is among the simplest types of financial forward contracts. You actually exchange (like going through the money-changer exactly once) the 2 amounts on a future date. This instrument is not tradable.

(An alternative form of outright is NDF, common for Chinese RMB. Money-changer 0 times i.e. never. It’s a cash-settled derivative just like FRA or IRS.)

The more complex forward instrument is the FX swap (I don’t mean “currency swap”, which is basically IRS). Tradable on interbank market. Money-Changer 2 times, on Near date and Far date. To understand the Need for FX swap, we need to understand rolling forward….

FX swap is like a repo — 2 legs, 2 settlement dates.

Important jargon/concepts in FX forward
* near date, far date
* near leg (usually “spot leg”), forward leg

Most FX forward contracts have a timeline of 1 to 12 months from trade date. Same for FX options.